在javascript中从外部函数访问内部变量
问题描述:
是否可以从外部函数访问内部变量,如此示例?
Is it possible to access an inner variable from an external function like this example?
function a(f) {
var c = 'test';
f();
}
a(function() {
alert(c); //at this point, c should = "test"
});
答
不,这不行。重要的是(词汇上)一个函数定义,而不是调用的地方。
No, that won't work. What matters is where (lexically) a function is defined, not where it's invoked.
当弄清楚什么是(如果有的话)c指的是,语言在本地范围内查找,然后在下一个范围中基于函数的定义。因此,如果在的另一个函数中调用a, 具有自己的本地c,则该值将是警报显示的内容。
When figuring out what (if anything) "c" refers to, the language looks in the local scope, then in the next scope out based on the definition of the function. Thus if that invocation of "a" took place in another function that did have its own local "c", then that value would be what the alert showed.
function b() {
var c = 'banana';
a(function() {
alert(c);
});
}
b(); // alert will show "banana"