开发者

Accessing variable in outer scope?

(function开发者_开发百科 () {
    var x = 1;
    return {
        f: function (x) {
            alert(x);
        }
    };
}()).f(2);

Suppose I don't want to rename either variable. There is no way to, from within f, access the variable x, which was declared first - right?


Correct. Because you have a different x in function (x), any attempt to access x will get that one (the nearest scope). It blocks access to any x in a wider scope.


This allows you to use both x (1) and x (2) at the same time.

(function () {
    var x = 1;
    return {
        f: function (x) {
            alert(x); // paramter (=2)
            alert(this.x); // scoped variable (=1)
        },
        x:x
    };
}()).f(2);


You could return the variable with the function:

(function () {
    var x = 1;
    return {
        f: function () {
            alert(this.x);
        },
        x:x
    };
}()).f();


There is no way to, from within f, access the variable x, which was declared first

No, there is not. The inner scope x hides the outer scope x.

var closure = (function () {
    var local = {};
    local.x = 1;
    return {
        f: function (x) {
            alert(x || local.x);
        }
    };
}());

closure.f(2);  // alerts "2"
closure.f();   // alerts "1"

You can't have an inner variable called "local", of course. ;-)


Aware of implicit async calls which make you think that you can't access of variable from outer scope:

result = {}
jQuery.ajax({ // it is a async call!
    url: "/some/url",
    success: function(data) {
        result = JSON.parse(data);
    }
});

return result; // Result will be still {} because function returns before request has done.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜