,我会尽量给你的代码一个不错的解释权:
function counter() {
var count = 0;
// By calling the function counter (adding a '()' after its name) you are returning a brand new anonymous function
return function() { // **Reference 1**
alert(count++);
}
}
// Here, the count variable is actually the anonymous function you returned in the **Reference 1**
var count = counter();
// In this line, you are calling the anonymous function (adding the '()' after its new name 'count')
count();
上述解释解释为什么这个工程。因为,首先你调用了一个函数,它返回一个匿名函数并将其分配给变量计数。然后你通过在其名称后面加上'()'来调用该函数,该函数执行alert(count++)
现在,为什么其他示例不起作用?我想,现在是很明显:
var count = function() {
var count = 0;
return function() { // **Reference 2**
alert(count++);
}
};
// Here you are calling the count function which returns the anonymous function in the line **Reference 2**.
count(); // So, long story short, this call only returns the anonymous function.
你应该尝试第二“()”后增加:count()();
。这应该也可以,因为第一个'()'返回匿名函数,第二个执行返回的匿名函数。
希望这会有所帮助!
非常感谢大家,所有的答案都很有帮助,我只是很感激在这里额外付出代价,并在代码中解释答案,我现在完全明白了。 – SeptimaEspada
很棒@SeptimaEspada。这是一个非常简单的概念,对于Javascript高级编程非常有用。非常乐意帮助你! :) – wilsotobianco