Home  >  Article  >  Web Front-end  >  Let’s take a good look at closures in JavaScript!

Let’s take a good look at closures in JavaScript!

coldplay.xixi
coldplay.xixiforward
2020-10-21 17:41:221689browse

TodayJavaScript column introduces closures.

Let’s take a good look at closures in JavaScript!

Preface

If you want to learn JavaScript in depth, the concept of closure is almost unavoidable. Today Let us take a good look at what closure is.
If you are a beginner, you can read the previous article first to help you better understand the content of this article:

  • 【JavaScript】Interesting Scope and promotion

Understand closure

1. What is closure

Let’s first take a look at the definition of closure in MDN:

A function is bundled with a reference to its surrounding state (lexical environment, lexical environment) (or the function is surrounded by references). This combination is a closure.

The definition of closure is very obscure. If explained in a popular way, it is:

  • The combination of a function defined inside a function and its scope is called a closure .

This may still be very abstract, but we have a concept first, and this concept will be explained in detail below. For closures, there is actually another explanation:

  • An internal function is declared in a function and returned. The outside can access the internal value through this internal function. Such a function , we call it closure

Different from the first explanation, the second explanation calls the function itself a closure. This explanation is also reasonable, but to be more accurate, we can actually Call this function closure function. In this case, there is actually no problem with both interpretations, and they can exist at the same time.

2. Feel the closure

After reading the concept of closure, let’s feel it through actual examples. What does closure look like? What are the conditions for closure to occur?

What does a closure look like?

function outer(){    var a=0;    function inner(){        console.log(++a);
    }    return inner;
}var f=outer();
f();  //1f();  //2复制代码

Let’s first look at how closure is reflected in this example. We first define the outer function, and then declare an inner function inside the outer function and return it.

Externally, we execute the outer function and save the returned inner function in f, now fThis is what we call closure function.

In the example, we executed the f function twice and output 1 and 2 respectively, indicating that we are executing f#console.log(a); statement in a function, according to our previous explanation of scope, the variable will be found in the scope chain where the function is located, and finally in outerThis variable was found in the function and the value was added.

At the same time, it should be noted that the result we output is not

1 twice, indicating that our scope is shared and can be regarded as the scope of outer extended to the outside.

outer The scope should originally be released after execution, but according to the GC mechanism (we will not introduce it here) you will find:

  • I am ready to release outer, but the a variable seems to be referenced, and it is also saved externally. I don’t know when to call it? Okay, then I won’t release it yet.
The closure was born in this way.

After the scope disappears, the variables in the scope can still be accessed from the outside.

Conditions for closure generation?

Based on the examples and explanations just given, let’s summarize what conditions are needed to generate a closure:

  1. Declare an internal function in the external function and return the internal function. Here
    outer is the external function, and inner is the returned internal function.
  2. The internal function refers to the variables in the external function. In our example, the
    inner function refers to the variable a.
  3. The external function needs to be executed, a closure is created, and the returned internal function needs to be saved. External function
    outer needs to be executed, and the returned internal function needs to be saved, which is var f=outer() in our example.
Only when these three conditions are met at the same time can a closure be generated. It seems difficult to achieve, but in fact, closures can often be generated inadvertently in our actual code.

Through the introduction just now, I believe everyone should have a concept of closure. Next, let us set out to have an in-depth understanding of all aspects of closure.

Experience closures in depth

1. Create multiple closures

In the example just now, we created a closure and after executing the closure function multiple times , all the variables added are

a in the same scope, then what will happen if we try to create multiple closures:

function outer() {  var a = 0;  function inner() {    console.log(++a);
  }  return inner;
}var f1 = outer();var f2 = outer();
f1();  //1f2();  //1复制代码

这段代码在刚刚的例子上进行了改动,我们执行了两次外部函数outer,并分别用不同的变量f1f2保存。当执行f1f2时会发现,输出的结果都是1,说明f1f2的作用域是独立的,f1f2属于两个不同的闭包,我们用一张图来理解下:Let’s take a good look at closures in JavaScript!

当分别创建f1f2时,调用了两次outer函数,创建了两个不同的上下文。而当f1f2分别执行时,根据作用域的查找规则,会去对应的作用域中查找变量,并执行增值输出,所以最终两个值均为2

2.使用闭包实现模块化

我们知道,作用域的外部无法拿到作用域内部的值,而通过闭包,我们可以把作用域我们需要的值或者方法暴露出去,比如:

function outer() {  var myNumber = 0;  function addNumber() {
    myNumber++;
  }  function getNumber() {    return myNumber;
  }  return {
    addNumber, getNumber
  }
}var module = outer();module.addNumber();module.addNumber();module.getNumber();复制代码

在这个例子中,我们同样定义了一个外部函数outer,另外还分别定义了两个函数addNumbergetNumber,用于增加和获取变量myNumber

当我们执行outer()语句的时候,会创建一个上下文,同时把内部返回的对象保存在module变量上,此时我们就创建了一个闭包,以及一个包含方法addNumbergetNumber的对象。

由于外部是无法直接访问变量myNumber的,但由于闭包的原因,addNumbergetNumber是可以访问到这个变量的,因此我们成功的把变量myNumber隐藏了起来,并且对外只提供了增加和获取myNumber值的方法。

试着用闭包解决问题

通过刚刚的例子,相信大家应该对闭包有了一定了解,接下来我们试着运用闭包来解决实际问题,先看一下例子:

for (var i = 0; i < 2; i++) {      setTimeout(() => {        console.log(i);
      }, 500);
    }复制代码

这是一个十分容易令人误解的例子。接触过的小伙伴肯定都知道,最后会输出两次2而不是依次输出01,我们来看看为什么会这样。
首先,外部是一个for循环,执行了两次语句。

for (var i = 0; i < 2; i++) {
    ... //  执行两次}复制代码

在函数的内部,我们调用了setTimeout函数,关键的地方来了,这个函数是一个异步函数,并不会马上执行,所以实际上等外部的for循环执行结束了,才会真的执行setTimeout中的函数。还有第二个关键点在于,for循环中,var定义的变量相当于定义在全局,而不存在块级作用域。那么刚刚的代码就可以近似的看成这样了。

var i=0;
i++;    //i=1i++;    //i=2console.log(i);console.log(i);复制代码

非常直接粗暴,但可以很清晰的看出输出结果为何是两次2了,因为大家共用了同一个作用域,i的值被覆盖了。那么知道了问题出在哪里,我们试着用上我们刚刚学习的闭包,来创建不同的作用域:

   for (var i = 0; i < 2; i++) {      function outer() {        var j = i;        setTimeout(function inner() {          console.log(j);
        }, 500);
      }
      outer();
    }复制代码

我们按照闭包的样式对刚刚的代码进行了改造,这里的setTimeout并不直接就是inner函数,这是因为它在这里起到了定义inner函数,并保存执行inner函数的功能。

我们可以看到,最终结果依次输出了01,说明我们的闭包是成功了的,但这样的闭包比较臃肿,我们试着提高一下,写的更加优雅一点:

   for (var i = 0; i < 2; i++) {
        (function() {   //用自执行函数代替了`outer`函数的定义和执行两个步骤
            var j = i;            setTimeout(function inner() {                console.log(j);
            }, 500);
        })();
    }复制代码

还可以再简化一下:

for (var i = 0; i < 5; i++) {        for (var i = 0; i < 2; i++) {
            (function(j) {//用自执行函数代替了`outer`函数的定义和执行两个步骤
                setTimeout(function inner() {                    console.log(j);
                }, 500);
            })(i);//var j=i的步骤,通过传入i值替换
        }
    }复制代码

这样就大功告成了!

总结

本篇首先介绍了闭包的定义以及不同人对闭包的理解,之后介绍了闭包产生的原因并总结了三个条件,之后举例说明了如何创建多个闭包和通过闭包实现模块,最后讲述了如何通过闭包解决for循环中使用异步函数依次输出值的问题。其实闭包没有想象的那么可怕,只要你愿意静下心去探索去了解,闭包也会对你敞开大门~

写在最后

都看到这里了,如果觉得对你有帮助的话不妨点个赞支持一下呗~

以后会陆续更新更多文章和知识点,感兴趣的话可以关注一波~

如果哪里有错误的地方或者描述不准确的地方,也欢迎大家指出交流~

相关免费学习推荐:javascript(视频)

The above is the detailed content of Let’s take a good look at closures in JavaScript!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete