JS closure principle

Closures in JavaScript Advanced Programming (3rd edition) are described: the closure is a function of another function has access to variables of the scope.

So the role of closures will be obvious.

1. can access the local variables inside a function of the external function. 
2. Let these variables are always stored in the memory, and not as the end of the function is automatically destroyed.

Closure representation forms, for example where:

function foo() {
   var a = 10;
   function bar() {
    a *= 2;
    return a;
   }
   return bar;
}
var baz = foo(); // baz is now a reference to function bar.
console.log(baz()); // returns 20.
console.log(baz()); // returns 40.
console.log(baz()); // returns 80.
var blat = foo(); // blat is another reference to bar.
console.log(blat()); // returns 20, because a new copy of a is being used.

  Example, baz and a copy of the balt each have their own scope and a, and only they can modify it.

 

       The so-called "closure" is further defined as a function of the target object constructor function in vivo method, and a method for this object in turn refers to a temporary variable outer function body.

This makes the long lifetime of the target object always able to maintain its methods, it can indirectly keep the temporary variables was used in the original constructor body values.

        The constructor calls despite the very beginning has been completed, the name of the temporary variable also are gone, but in the method of the target object has always been able to refer to the value of the variable, and only through this method to access the value.

Even if the constructor call the same again, but will only generate new objects and methods, just a new temporary variable corresponding to the new value, and is independent of that last call

 

Third, the closure Precautions

1) Due to the closure 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.

 

 

 

Guess you like

Origin www.cnblogs.com/651434092qq/p/12525336.html