简体   繁体   中英

JS closure - reinitializing confusion

I have referred to multiple links for this concept but it is little bit tricky to wrap the concept around the head completely.

I was going through and example of it on https://www.w3schools.com/js/js_function_closures.asp

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

add();
add();
add(); //Counter is 3

But isn't every time this is getting called counter is getting reinitialized to 0? Can someone use table or something to help me understand every step here?

What add holds is returned function in the IIFE. ( https://developer.mozilla.org/en-US/docs/Glossary/IIFE )

function () {counter += 1; return counter}

So calling add doesn't reinitialize counter .

 var add = (function() { var counter = 0; return function() { counter += 1; return counter } })(); console.log(add()); console.log(add()); console.log(add());

 var addHandler = function() { var counter = 0; return function() { counter += 1; return counter } }; const add = addHandler(); // return inner function console.log(add()); console.log(add()); console.log(add());

In javascript, functions have their own execution environment.

And the execution environment is created when the function is called and disappears when execution is complete.

In the code above, the value in "add" becomes the new function returned after the IIFE function is executed.

In other words, the execution environment of the IIFE function has already been executed and disappeared.

However, the inner returned function is still looking at the parent function's variable "counter".

Previously, it was said that the environment disappears when the function is called. In this case, the remembering the environment of the parent function is called a'closure'.


IIFE is an immediate function.

Functions are declared and called when necessary in the form of "function name()".

The IIFE above will execute the function right away by declaring the function and wrapping it in "()".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM