看看這段代碼
function createCounter(){
var index = 0; //initialize the index
//returns a closure that increments the index,
//and returns the value on every invocation
return function(){ return ++index; }
}
//crete an "instance" of a counter
var aCounter = createCounter();
//and invoke it a few times
console.log("a", aCounter());
console.log("a", aCounter());
console.log("a", aCounter());
//create another counter, and invoke it
var anotherCounter = createCounter();
console.log("b", anotherCounter());
console.log("b", anotherCounter());
//showing that they increment independent of each other
console.log("a", aCounter());
console.log("a", aCounter());
這將是一個「好」實施這一效用的,因爲你可以一遍又一遍使用它,不重複自己。
如果你直接調用createCounter
,你會得到你的代碼示例。
var aCounter = (function(){
var index = 0;
return function(){ return ++index }
})();
你能在問題本身提供代碼嗎? – evolutionxbox
_「分配給函數的調用_」,沒有它被分配返回的函數表達式'function(){return counter + = 1;}' –
由於JS關閉,返回的函數可以訪問活動計數器變量。這是JS最強大的功能之一。 – evolutionxbox