Home > Article > Web Front-end > Let's take a good look at closures in JavaScript!
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:
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:
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:
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.
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?
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 f
This 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.
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:
, 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.
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: is the external function, and
inner is the returned internal function.
function refers to the variable
a.
needs to be executed, and the returned internal function needs to be saved, which is
var f=outer() in our example.
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
,并分别用不同的变量f1
和f2
保存。当执行f1
和f2
时会发现,输出的结果都是1
,说明f1
和f2
的作用域是独立的,f1
和f2
属于两个不同的闭包,我们用一张图来理解下:
当分别创建f1
和f2
时,调用了两次outer
函数,创建了两个不同的上下文。而当f1
和f2
分别执行时,根据作用域的查找规则,会去对应的作用域中查找变量,并执行增值输出,所以最终两个值均为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
,另外还分别定义了两个函数addNumber
和getNumber
,用于增加和获取变量myNumber
。
当我们执行outer()
语句的时候,会创建一个上下文,同时把内部返回的对象保存在module
变量上,此时我们就创建了一个闭包,以及一个包含方法addNumber
和getNumber
的对象。
由于外部是无法直接访问变量myNumber
的,但由于闭包的原因,addNumber
和getNumber
是可以访问到这个变量的,因此我们成功的把变量myNumber
隐藏了起来,并且对外只提供了增加和获取myNumber
值的方法。
通过刚刚的例子,相信大家应该对闭包有了一定了解,接下来我们试着运用闭包来解决实际问题,先看一下例子:
for (var i = 0; i < 2; i++) { setTimeout(() => { console.log(i); }, 500); }复制代码
这是一个十分容易令人误解的例子。接触过的小伙伴肯定都知道,最后会输出两次2
而不是依次输出0
和1
,我们来看看为什么会这样。
首先,外部是一个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
函数的功能。
我们可以看到,最终结果依次输出了0
和1
,说明我们的闭包是成功了的,但这样的闭包比较臃肿,我们试着提高一下,写的更加优雅一点:
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!