I cannot understand the example of a closure

纵然是瞬间 提交于 2019-12-02 16:46:24

问题


Please me to understand the closures. Why does the counter work in the first variant, but in the second version there is not?

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

console.log(counter());
console.log(counter());
console.log(counter());

The counter outputs 0,1,2

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

console.log(counter()());
console.log(counter()());
console.log(counter()());

The counter outputs 0,0,0

What is the difference?


回答1:


In the first example, you are using an Immediately Inovked Function Expression. This is calling the function inline and assigning the resultant function to counter. Each time you call counter() you are calling that inner function which has the count variable in scope.

The second example is equivalent to writing as

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

When you write it this way, it's clearer that every time you call counter(), you are returning a new function with the count variable in scope

You could do the equivalent in the second example by assigning the result to a variable and calling that multiple times.

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

var counterObj = counter();

counterObj(); // returns 0
counterObj(); // returns 1
counterObj(); // returns 2



回答2:


In the first example, counter is assigned the return value of a self invoking function.

counter =(

In the first example, counter is called and it returns

return count++;.

In the second example, counter is a regular function, and when called begins at the declaration

var count=0;


来源:https://stackoverflow.com/questions/50611101/i-cannot-understand-the-example-of-a-closure

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