简体   繁体   English

访问外部范围内的变量?

[英]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? f ,没有办法访问变量x ,它是首先声明的 - 对吗?

Correct. 正确。 Because you have a different x in function (x) , any attempt to access x will get that one (the nearest scope). 因为function (x)有不同的x ,所以访问x任何尝试都将获得该值(最近的范围)。 It blocks access to any x in a wider scope. 它阻止访问更广泛范围内的任何x

This allows you to use both x (1) and x (2) at the same time. 这允许您同时使用x(1)和x(2)。

(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 f ,无法访问首先声明的变量x

No, there is not. 不,那里没有。 The inner scope x hides the outer scope x . 内部范围x隐藏外部范围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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM