Closure appreciated JS-

What is a closure?

Closures (closure) is a major difficulty javascript, but also its characteristics. Many advanced applications must rely on to achieve closure.
Closures people to feel in JS is a relatively vague concept, in fact, we usually write the code has been unwittingly used a lot of closure, I understand that the whole of the closure, external function when nested inner function, the function reference variable internal (function) of the external function, the closure is generated. In summary condition occurs closure comprises the following: 1, the nested function, 2, the function reference internal data (variable or function) of the external function, 3, the external function is called. Satisfies the above three conditions to produce closures.
For example, the following statement:

function f1(){
    var n="Joey_Tribiani";
    function f2(){
      console.log(n); //Joey_Tribiani
    }
    f2();
  }

This code actually has been achieved function closures, the variable n is defined outside the function f1 f2 internal functions, as they are called function f2 can use this variable, and therefore produce in line with the conditions we are talking about closures, which It is a simple closure.

The role of closures

Closures can be used in many places. It's most useful for two, one is the aforementioned variables can be read inside the function, and the other is to make the values ​​of these variables remain in memory and are not automatically cleared after f1 call. And because the variables are defined inside a function, this way it will not pollute the global namespace.

Why is this so? The reason is that the parent function f1 is f2, and f2 is assigned to a global variable, which leads to f2 is always in memory, and relies on the presence of f1 and f2, f1 therefore always in memory, and not after the end of the call , the garbage collection (garbage collection) recovered. (It is important to understand this)

Precautions closures are used

1, due to the closures will make the function of the variables are stored in memory, memory consumption is large, it can not be abused closure, otherwise it will cause performance problems webpage in IE may lead to memory leaks. The solution is, before exiting the function will delete all local variables are not used.

2, the closure will function outside the parent, the parent function changes the value of the internal variable. So, if you take the parent function as an object (object) to use, the closure of its public methods (Public Method) as, the internal variable as its private property (private value), then you must be careful not to just change the value of the parent function of internal variables.

Published 19 original articles · won praise 0 · Views 296

Guess you like

Origin blog.csdn.net/Joey_Tribiani/article/details/103543103