In-depth understanding of Javascript closures (Closure)

1. Variable Scope

To understand closures, Javascript must first understand the special variable scope.

Scope of a variable is nothing more than two ways:

  • Global Variables
  • Local variables

Javascript language so special, it is that internal function Global variables can be read directly.

  var n = 999;

  function f1(){
    alert(n);
  }

  f1(); // 999

On the other hand, can not be read outside the natural function of local variables within the function.

  function f1(){
    var n=999;
  }

  alert(n); // error

There is a need to pay attention, when you declare a variable inside a function, be sure to use the var command. If you do not, you actually declare a global variable!

  function f1(){
    n=999;
  }

  f1();

  alert(n); // 999

2. How to read a local variable from outside?

For various reasons, we sometimes need to get a local variable within the function. However, as already said, under normal circumstances, this can not be done, can be achieved only through alternative methods.

That it is, inside the function, and then define a function.

  function f1(){

    var n=999;

    function f2(){
      alert(n); // 999
    }

  }

In the above code, the function f2 are included in the internal functions f1, f1 time all local variables inside of f2 is visible. But the reverse is not, local variables inside of f2, f1 is to be invisible. This is the Javascript language-specific "scope chain" structure (chain scope), a sub-objects up to find all the variables of a parent object to. So 父对象的所有变量,对子对象都是可见的, not vice versa.

Since f1 f2 can be read in a local variable, so long as f2 as a return value, we can not read its internal variables outside f1 yet!

  function f1(){

    var n=999;

    function f2(){
      alert(n);
    }

    return f2;

  }

  var result=f1();

  result(); // 999

3. The concept of closures

A code on the f2 function is closure.

"Closure" on a variety of professional literature (closure) definition is very abstract, difficult to understand. I understand 闭包就是能够读取其他函数内部变量的函数that .

Since the Javascript language, only the internal function subroutine to read local variables, the closure can be simply interpreted as "a defined function within the function."

Therefore, in essence, the closure is an internal bridge function and the function of connecting external.

4. Use Closure

Closures can be used in many places. It's most useful for two

  • Function can read the internal variables
  • Let the values ​​of these variables remain in memory

How to understand it? Consider the following code.

  function f1(){

    var n=999;

    nAdd=function(){n+=1} //nAdd是全局变量且是匿名函数

    function f2(){ //闭包
      console.log(n);
    }

    return f2;

  }

  var result=f1();

  result(); // 999

  nAdd();

  result(); // 1000

In this code, result is actually a closure function f2. It operates a total of twice, the first time the value is 999, the second value is 1000. 函数f1中的局部变量n一直保存在内存中,并没有在f1调用后被自动清除This proves that .

Why is this so? The reason is that f1 and f2 is the parent function, but f2被赋给了一个全局变量,这导致f2始终在内存中rather depends on the existence of f1 and f2, f1 therefore always in memory, and not at the end of the call, the garbage collection (garbage collection) recovered.

This code is worth noting that in another place, is "nAdd=function(){n+=1}"this line, no first use of the var keyword in front nAdd, therefore nAdd是一个全局变量, rather than a local variable. Secondly, nAdd的值是一个匿名函数(anonymous function),而这个匿名函数本身也是一个闭包so is the equivalent of a nAdd the setter, it may operate on local variables inside a function outside the function.

5. Note that the point of closure

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 .

2)闭包会在父函数外部,改变父函数内部变量的值 . 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.

Six Questions

If you can understand the operating results of the following two pieces of code, it should be understood even if the operating mechanism of the closures.

A snippet.

  var name = "The Window";

  var object = {
    name : "My Object",

    getNameFunc : function(){
      return function(){
        return this.name;
      };

    }

  };

  alert(object.getNameFunc()());

Fragment II.

  var name = "The Window";

  var object = {
    name : "My Object",

    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };

    }

  };

  alert(object.getNameFunc()());

reference

  1. https://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html
Published 148 original articles · won praise 136 · Views 250,000 +

Guess you like

Origin blog.csdn.net/DlMmU/article/details/104711300