我有这段简单的代码:
function test(){
var test_array = []
return function(i){
test_array.push(i);
alert(test_array.length);
};
}
由于上下文绑定(bind)到闭包,我希望代码在每次调用匿名函数时更新数组的长度。然而这并没有发生。如果我像这样多次调用闭包:
test()(1);
test()(2);
警报始终显示长度为 1。
你能解释一下为什么吗?
谢谢
最佳答案
每次调用 test
都会创建一个 new 执行上下文,其中包含一个 new 数组和一个 new 关闭函数该上下文(包括数组)。
如果您保存对函数 test
返回的引用,然后重复调用同一函数,它将更新通过调用创建该函数的 test
创建的数组,你会看到你所期望的:
var f = test();
f(); // 1
f(); // 2
或者当然,您可以有多个:
var first = test();
var second = test();
first(); // 1
first(); // 2
first(); // 3
second(); // 1
first(); // 4
关于javascript - 更新 Javascript 闭包中的上下文数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20967301/