问题
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