【发布时间】:2015-07-24 09:50:04
【问题描述】:
我阅读了How do JavaScript closures work? 问题并认为我终于理解了闭包。
尤其是这一点现在非常令人困惑:
示例 7
最后一个例子表明,每次调用都会为局部变量创建一个单独的闭包。每个函数声明都没有一个闭包。每次调用函数都有一个闭包。 ......................................
好的,示例 7 显示了这个示例:
function newClosure(someNum, someRef) {
// Local variables that end up within closure
var num = someNum;
var anArray = [1,2,3];
var ref = someRef;
return function(x) {
num += x;
anArray.push(num);
document.write('num: ' + num +
'; anArray: ' + anArray.toString() +
'; ref.someVar: ' + ref.someVar + "<br>");
}
}
obj = {someVar: 4};
fn1 = newClosure(4, obj);
fn2 = newClosure(5, obj);
fn1(1); // num: 5; anArray: 1,2,3,5; ref.someVar: 4;
fn2(1); // num: 6; anArray: 1,2,3,6; ref.someVar: 4;
obj.someVar++;
fn1(2); // num: 7; anArray: 1,2,3,5,7; ref.someVar: 5;
fn2(2); // num: 8; anArray: 1,2,3,6,8; ref.someVar: 5;
这个例子对我很有效。
所以我做了一点实验,我真的不明白为什么这段代码不起作用(看起来它甚至没有在函数调用上创建一个新的闭包)
function createCounter(startValue){
var localCounter;
this.setCounter = function(firstValue) {
localCounter = firstValue;
}
this.getValue = function(){return localCounter;};
this.increment = function(){localCounter++;};
this.setCounter(startValue);
return this;
}
var Counter1 = createCounter(1);
document.write(Counter1.getValue()); //1
Counter1.increment();
var Counter1Value = Counter1.getValue(); // 2
var Counter0 = createCounter(0); //works as it should if i put a "new createCounter(0) here, but why?
document.write("<br >Counter 1 oldValue:" + Counter1Value); //2
document.write("<br >Counter 1 currentValue:" + Counter1.getValue()); //0 (why is the localvariable overwritten?)
document.write("<br >Counter 0 currentValue:" + Counter0.getValue()); // //0
为什么我需要添加“new”关键字来创建第二个闭包,为什么 Counter1 和 Counter0 都使用相同的 localCounter 变量?
【问题讨论】:
-
这与
new的关系比闭包更多。我建议阅读this的工作原理。
标签: javascript closures this