Making counter using closure and self-invoking function

巧了我就是萌 提交于 2019-12-20 07:10:04

问题


I'm wondering why this code doesn't work,

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

console.log(uniqueInteger()());  // 0
console.log(uniqueInteger()());  // 0
console.log(uniqueInteger()());  // 0 
console.log(uniqueInteger()());  // 0

and this code does. The only difference is making the function self invoked instead of invoking it in console.log()

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

console.log(uniqueInteger());  // 0
console.log(uniqueInteger());  // 1
console.log(uniqueInteger());  // 2 
console.log(uniqueInteger());  // 3

I'm very new to JS so please excuse my noobness. Thanks!


回答1:


The second code created a closure with var counter = 0 only once since when defining uniqueInteger, it called a function that returned a function where initialization is done. The first code creates var counter = 0 every time you call it.

Note that with the first code you can do:

ui = uniqueInteger();
console.log(ui()); // 0
console.log(ui()); // 1
ui2 = uniqueInteger();
console.log(ui()); // 2
console.log(ui2()); // 0
console.log(ui()); // 3
console.log(ui2()); // 1


来源:https://stackoverflow.com/questions/17910196/making-counter-using-closure-and-self-invoking-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!