像这个例子一样,是否有可能从外部函数访问内部变量?
function a(f) {
var c = 'test';
f();
}
a(function() {
alert(c); //at this point, c should = "test"
});
像这个例子一样,是否有可能从外部函数访问内部变量?
function a(f) {
var c = 'test';
f();
}
a(function() {
alert(c); //at this point, c should = "test"
});
function b() {
var c = 'banana';
a(function() {
alert(c);
});
}
b(); // alert will show "banana"
这样是行不通的,因为变量c
是在函数内部定义的,无法在函数外部使用。但可以通过将变量c
作为参数传递给提供给a
的函数。
function a(f) {
var c = 'test';
f(c);
}
a(function(c) {
alert(c); //at this point, c should = "test"
});
像其他人所说的,这是不可能的。你可以
1. 在函数范围之外声明变量
2. 向f
传递一个参数:
function a(f) { var c = { name: 'test' }; f(c) };
a(function(o) { alert(o.name) })