在JS中调用闭包

时间:2016-04-30 15:39:12

标签: javascript closures

我是JS的新手,以及这个JS闭包示例

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

我无法理解变量add被赋予函数调用的原因,而不是函数本身。 换句话说,现在add应该引用一个被调用的函数,并且为了调用add,我们不需要在最后添加(),它已被调用。 为什么示例如下所示:add()?我无法找到它的确切术语,但这并不像是双重调用'功能?

1 个答案:

答案 0 :(得分:0)

看一下这段代码

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 }
})();