Home > Web Front-end > JS Tutorial > JavaScript has an in-depth understanding of js closures

JavaScript has an in-depth understanding of js closures

不言
Release: 2018-03-31 15:12:30
Original
2609 people have browsed it

Closure (closure) is a difficulty and characteristic of the Javascript language. Many advanced applications rely on closures. This article shares with you an in-depth understanding of js closures. Interested friends can refer to

1. Scope of variables

To understand closures, you must first understand Javascript's special variable scope.

The scope of variables is nothing more than two types: global variables and local variables.

The special thing about the Javascript language is that global variables can be read directly inside the function.


Js code

 

 var n=999;
  function f1(){
    alert(n);
  }
  f1(); // 999
Copy after login

On the other hand, local variables within the function cannot be read outside the function.

Js code

 

function f1(){
    var n=999;
  }
  alert(n); // error
Copy after login

There is one thing to note here. When declaring variables inside a function, you must use the var command. If you don't use it, you are actually declaring a global variable!

Js code

 

 function f1(){
    n=999;
  }
  f1();
  alert(n); // 999
Copy after login

-------------------------- -------------------------------------------------- ----------------------------

2. How to read from the outside Local variables?

For various reasons, we sometimes need to get local variables within a function. However, as mentioned before, this is not possible under normal circumstances and can only be achieved through workarounds.

That is to define another function inside the function.

Js code

 

 function f1(){
    n=999;
    function f2(){
      alert(n); // 999
    }
  }
Copy after login

In the above code, function f2 is included inside function f1. At this time, all local variables inside f1 are for f2 visible. But the reverse doesn't work. The local variables inside f2 are invisible to f1. This is the "chain scope" structure unique to the Javascript language.

The child object will search for the variables of all parent objects level by level. Therefore, all variables of the parent object are visible to the child object, but not vice versa.

Since f2 can read the local variables in f1, then as long as f2 is used as the return value, can't we read its internal variables outside f1?


Js code

 

 function f1(){
    n=999;
    function f2(){
      alert(n);
    }
    return f2;
  }
  var result=f1();
  result(); // 999
Copy after login

----------------- -------------------------------------------------- --------------------------------

3. The concept of closure

The f2 function in the code in the previous section is a closure.

The definition of "closure" in various professional literature is very abstract and difficult to understand. My understanding is that a closure is a function that can read the internal variables of other functions.

Since in the Javascript language, only sub-functions inside the function can read local variables, closures can be simply understood as "functions defined inside a function".

So, in essence, closure is a bridge connecting the inside of the function and the outside of the function.

---------------------------------------- -------------------------------------------------- -------------b

4. The purpose of closure

Closure can be used in many places. It has two greatest uses. One is to read the variables inside the function as mentioned earlier, and the other is to keep the values ​​of these variables in memory.

How to understand this sentence? Please look at the code below.


Js code

 

 function f1(){
    var n=999;
    nAdd=function(){n+=1}
    function f2(){
      alert(n);
    }
    return f2;
  }
  var result=f1();
  result(); // 999
  nAdd();
  result(); // 1000
Copy after login

In this code, result is actually the closure f2 function. It was run twice, the first time the value was 999, the second time the value was 1000. This proves that the local variable n in function f1 is always stored in memory and is not automatically cleared after f1 is called.

Why is this so? The reason is that f1 is the parent function of f2, and f2 is assigned to a global variable, which causes f2 to always be in memory, and the existence of f2 depends on f1, so f1 is always in memory and will not be deleted after the call is completed. , recycled by the garbage collection mechanism (garbage collection).

Another thing worth noting in this code is the line "nAdd=function(){n+=1}". First of all, the var keyword is not used before nAdd, so nAdd is a global variable. rather than local variables. Secondly, the value of nAdd is an anonymous function, and this

anonymous function itself is also a closure, so nAdd is equivalent to a setter, which can operate on local variables inside the function outside the function.

---------------------------------------- -------------------------------------------------- -------------

5. Points to note when using closures

1) Since closures will cause the variables in the function to be stored in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems on the web page, and may lead to memory leaks in IE. The solution is to delete all unused local variables before exiting the function.

2)闭包会在父函数外部,改变父函数内部变量的值。所以,如果你把父函数当作对象(object)使用,把闭包当作它的公用方法(Public Method),把内部变量当作它的私有属性(private value),这时一定要小心,不要随便

改变父函数内部变量的值。

--------------------------------------------------------------------------------------------------------

六、思考题

如果你能理解下面代码的运行结果,应该就算理解闭包的运行机制了。

Js代码
  

var name = "The Window";   
  var object = {   
    name : "My Object",   
    getNameFunc : function(){   
      return function(){   
        return this.name;   
     };   
    }   
};   
alert(object.getNameFunc()());  //The Window
Copy after login

--------------------------------------------------------------------------------------------------------
JavaScript闭包例子

function outerFun()
 {
  var a=0;
  function innerFun()
  {
   a++;
   alert(a);
  }    
 }
innerFun()
Copy after login

上面的代码是错误的.innerFun()的作用域在outerFun()内部,所在outerFun()外部调用它是错误的.

改成如下,也就是闭包:

Js代码

function outerFun()
{
 var a=0;
 function innerFun()
 {
  a++;
  alert(a);
 }
 return innerFun;  //注意这里
}
var obj=outerFun();
obj();  //结果为1
obj();  //结果为2
var obj2=outerFun();
obj2();  //结果为1
obj2();  //结果为2
Copy after login

什么是闭包:

当内部函数 在定义它的作用域 的外部 被引用时,就创建了该内部函数的闭包 ,如果内部函数引用了位于外部函数的变量,当外部函数调用完毕后,这些变量在内存不会被 释放,因为闭包需要它们.

--------------------------------------------------------------------------------------------------------

再来看一个例子

Js代码

function outerFun()
{
 var a =0;
 alert(a);  
}
var a=4;
outerFun();
alert(a);
Copy after login

结果是 0,4 . 因为在函数内部使用了var关键字 维护a的作用域在outFun()内部.

再看下面的代码:

Js代码

function outerFun()
{
 //没有var 
 a =0;
 alert(a);  
}
var a=4;
outerFun();
alert(a);
Copy after login

结果为 0,0 真是奇怪,为什么呢?

作用域链是描述一种路径的术语,沿着该路径可以确定变量的值 .当执行a=0时,因为没有使用var关键字,因此赋值操作会沿着作用域链到var a=4; 并改变其值.

--------------------------------------------------------------------------------------------------------------------------------------------------

如果你对javascript闭包还不是很理解,那么请看下面转载的文章:(转载:http://www.felixwoo.com/archives/247)

一、什么是闭包?

官方”的解释是:闭包是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分。
相信很少有人能直接看懂这句话,因为他描述的太学术。其实这句话通俗的来说就是:JavaScript中所有的function都是一个闭包。不过一般来说,嵌套的function所产生的闭包更为强大,也是大部分时候我们所谓的“闭包”。看下面这段代码:

 a  
 i   
 b  i  
 b c  ac
Copy after login

这段代码有两个特点:

1、函数b嵌套在函数a内部;

2、函数a返回函数b。

引用关系如图:

JavaScript has an in-depth understanding of js closures

  这样在执行完var c=a()后,变量c实际上是指向了函数b,再执行c()后就会弹出一个窗口显示i的值(第一次为1)。这段代码其实就创建了一个闭包,为什么?因为函数a外的变量c引用了函数a内的函数b,就是说:

  当函数a的内部函数b被函数a外的一个变量引用的时候,就创建了一个闭包。

  让我们说的更透彻一些。所谓“闭包”,就是在构造函数体内定义另外的函数作为目标对象的方法函数,而这个对象的方法函数反过来引用外层函数体中的临时变量。这使得只要目标 对象在生存期内始终能保持其方法,就能间接保持原构造函数体当时用到的临时变量值。尽管最开始的构造函数调用已经结束,临时变量的名称也都消失了,但在目 标对象的方法内却始终能引用到该变量的值,而且该值只能通这种方法来访问。即使再次调用相同的构造函数,但只会生成新对象和方法,新的临时变量只是对应新 的值,和上次那次调用的是各自独立的。

二、闭包有什么作用?

  简而言之,闭包的作用就是在a执行完并返回后,闭包使得Javascript的垃圾回收机制GC不会收回a所占用的资源,因为a的内部函数b的执行需要依赖a中的变量。这是对闭包作用的非常直白的描述,不专业也不严谨,但大概意思就是这样,理解闭包需要循序渐进的过程。

在上面的例子中,由于闭包的存在使得函数a返回后,a中的i始终存在,这样每次执行c(),i都是自加1后alert出i的值。

  那 么我们来想象另一种情况,如果a返回的不是函数b,情况就完全不同了。因为a执行完后,b没有被返回给a的外界,只是被a所引用,而此时a也只会被b引 用,因此函数a和b互相引用但又不被外界打扰(被外界引用),函数a和b就会被GC回收。(关于Javascript的垃圾回收机制将在后面详细介绍)

三、闭包内的微观世界

  如果要更加深入的了解闭包以及函数a和嵌套函数b的关系,我们需要引入另外几个概念:函数的执行环境(excution context)、活动对象(call object)、作用域(scope)、作用域链(scope chain)。以函数a从定义到执行的过程为例阐述这几个概念。

  1. 定义函数a的时候,js解释器会将函数a的作用域链(scope chain)设置为定义a时a所在的“环境”,如果a是一个全局函数,则scope chain中只有window对象。

  2. 执行函数a的时候,a会进入相应的执行环境(excution context)

  3. 在创建执行环境的过程中,首先会为a添加一个scope属性,即a的作用域,其值就为第1步中的scope chain。即a.scope=a的作用域链。

  4. 然后执行环境会创建一个活动对象(call object)。活动对象也是一个拥有属性的对象,但它不具有原型而且不能通过JavaScript代码直接访问。创建完活动对象后,把活动对象添加到a的作用域链的最顶端。此时a的作用域链包含了两个对象:a的活动对象和window对象。

  5. 下一步是在活动对象上添加一个arguments属性,它保存着调用函数a时所传递的参数。

  6. 最后把所有函数a的形参和内部的函数b的引用也添加到a的活动对象上。在这一步中,完成了函数b的的定义,因此如同第3步,函数b的作用域链被设置为b所被定义的环境,即a的作用域。

到此,整个函数a从定义到执行的步骤就完成了。此时a返回函数b的引用给c,又函数b的作用域链包含了对函数a的活动对象的引用,也就是说b可以访问到a中定义的所有变量和函数。函数b被c引用,函数b又依赖函数a,因此函数a在返回后不会被GC回收。

当函数b执行的时候亦会像以上步骤一样。因此,执行时b的作用域链包含了3个对象:b的活动对象、a的活动对象和window对象,如下图所示:

JavaScript has an in-depth understanding of js closures

如图所示,当在函数b中访问一个变量的时候,搜索顺序是:

  1. 先搜索自身的活动对象,如果存在则返回,如果不存在将继续搜索函数a的活动对象,依次查找,直到找到为止。

  2. 如果函数b存在prototype原型对象,则在查找完自身的活动对象后先查找自身的原型对象,再继续查找。这就是Javascript中的变量查找机制。

  3. 如果整个作用域链上都无法找到,则返回undefined。

小结,本段中提到了两个重要的词语:函数的定义执行。文中提到函数的作用域是在定义函数时候就已经确定,而不是在执行的时候确定(参看步骤1和3)。用一段代码来说明这个问题:

 fx  
 g      x    g h  fh
Copy after login

这段代码中变量h指向了f中的那个匿名函数(由g返回)。

  • 假设函数h的作用域是在执行alert(h())确定的,那么此时h的作用域链是:h的活动对象->alert的活动对象->window对象。

  • 假设函数h的作用域是在定义时确定的,就是说h指向的那个匿名函数在定义的时候就已经确定了作用域。那么在执行的时候,h的作用域链为:h的活动对象->f的活动对象->window对象。

如果第一种假设成立,那输出值就是undefined;如果第二种假设成立,输出值则为1。

The running results prove that the second assumption is correct, indicating that the scope of the function is indeed determined when the function is defined.

4. Application scenarios of closures
Protect the security of variables within functions. Taking the initial example as an example, i in function a can only be accessed by function b and cannot be accessed through other means, thus protecting the security of i.

  1. Maintain a variable in memory. Still as in the previous example, due to closure, i in function a always exists in memory, so every time c() is executed, i will be incremented by 1.

  2. Implement JS private properties and private methods by protecting the security of variables (cannot be accessed externally)
    Private properties and methods cannot be accessed outside the Constructor


    function Constructor(...) {
    var that = this;
    var membername = value;
    function membername(...) {...}
    }

#The above three points are the most basic application scenarios of closures, and many classic cases originate from them.

5. Javascript’s garbage collection mechanism

In Javascript, If an object is no longer referenced, the object will be recycled by GC. If two objects refer to each other and are no longer referenced by a third party, then the two objects that refer to each other will also be recycled. Because function a is referenced by b, and b is referenced by c outside a, this is why function a will not be recycled after execution.

6. Conclusion

Understanding JavaScript closures is the only way to become an advanced JS programmer , only by understanding its explanation and operating mechanism can we write safer and more elegant code.

Related recommendations:

The use of JS closures

Characteristic analysis of JS closures

A simple understanding of js closure

The above is the detailed content of JavaScript has an in-depth understanding of js closures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template