因爲每次調用outerFun()
時候,你正在創建一個不同的新的執行上下文定義的,因此innerFun
是不是真的一樣事情,因爲您從outerFun
返回的innerFun
的每個函數引用都處於不同的上下文中,而上下文有其自己的變量。
function outerFun()
{
var a=0;
function innerFun()
{
a++;
alert(a);
}
return innerFun;
}
var obj = outerFun();
var obj2 = outerFun();
console.log(obj === obj2);
// Not equal, because innerFun is a different innerFun for each function call,
// as it is the same function name, returned from the same function,
// but in a different context.
obj(); //1
obj(); //2
obj2(); //1
obj2(); //2
// Call obj twice, it'll increase to 4.
// While calling obj2 once again, leaves it at 3.
// This way you can know that obj and obj2 are not modifying
// the same variables.
// They are independent of each other.
obj(); // 3
obj(); // 4
obj2(); // 3
如果答案解決了您的問題,您可以[單擊該答案上的複選標記以將問題標記爲已解決](http://meta.stackexchange.com/q/5234)。 – apsillers