Making counter using closure and self-invoking function

后端 未结 1 521
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-27 06:49

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

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

console.log(uni         


        
1条回答
  •  醉梦人生
    2021-01-27 07:44

    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
    

    0 讨论(0)
提交回复
热议问题