Look a little problem closures

Look through a small problem closure

var test = (function (){
var number = 4;
return function(){
number *= 2;
console.log(number);
}
})()

test();//8
test();//16
test();//32

Another method of comparison

var test = function (){
var number = 4;
return function(){
number *= 2;
console.log(number);
}
}

test()();//8
test()();//8
test()();//8

Conclusion: You can see the difference between these two places if the formation of the closure, on the outside can be a closure of the internal changes.
But if it is already the end of the return, although also considered closures (test () ()) , but it has a separate area.

It can be said the first case, is that we share a variable (number) closure, but the second one is independent. (If so inclined)

Guess you like

Origin www.cnblogs.com/asdfq/p/10994206.html