What is the javascript closures?

In our development, it is often used to closures, but when someone asked what is closure, it will probably not know. Then talk about some fundamental:

A. Understand the concept of closure,

Simply put, when nested function in function, inside the function can access external function in the variables, and function of the internal variables can not directly access the external function, when you return is an internal function, is a closure. See following example illustrates:

1. nested functions can access external variable declarations.

 function fn(x) {
      var z = 1;
      function fnc(y) {
        Alert (X + Y + (Z ++)); // Alert 7 
      }
      fnc(2);
    }
    fn(3)
fnc parameters may be accessed fn x, fn can access to the variable z, but this is not the closure.

2. External variables into local variables declared in the acquired variables for

 
 
function fn(x) {
There z = 1;
return function (y) {
alert (x + y + (++ z)); // alert 7
}
}
var bar = fn (2); // bar is now a closure
bar(3);

In fact, since the closure understand the concept of true costs, personal understanding is this: closure is the function of the internal variables can be read by other function is to bridge internal functions and external functions connected.

 

two. Closures pros and cons

 benefit:

1. Protection of the variables in the security function, to realize the package, to prevent inflow of other environmental variable name clashes,

2. self-executing anonymous function can reduce memory consumption, self-executing anonymous function passed in a function closure, self-executing anonymous function is executed completely destroyed immediately, you can reduce memory consumption.

Disadvantages: referenced private variable can not be destroyed, increased memory consumption, resulting in a memory leak.


Learn closures in more detail, please refer to the link: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures

 

Guess you like

Origin www.cnblogs.com/lwming/p/11025578.html