search
HomeWeb Front-endJS TutorialLet's take a good look at closures in JavaScript!

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  {        console.log(i);
      }, 500);
    }复制代码

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

for (var i = 0; i <p>在函数的内部,我们调用了<code>setTimeout</code>函数,关键的地方来了,<strong>这个函数是一个异步函数,并不会马上执行</strong>,所以实际上等外部的<code>for</code>循环执行结束了,才会真的执行<code>setTimeout</code>中的函数。还有第二个关键点在于,<strong>在<code>for</code>循环中,<code>var</code>定义的变量相当于定义在全局,而不存在块级作用域</strong>。那么刚刚的代码就可以近似的看成这样了。</p><pre class="brush:php;toolbar:false">var i=0;
i++;    //i=1i++;    //i=2console.log(i);console.log(i);复制代码

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

   for (var i = 0; i <p>我们按照闭包的样式对刚刚的代码进行了改造,<strong>这里的<code>setTimeout</code>并不直接就是<code>inner</code>函数,这是因为它在这里起到了定义<code>inner</code>函数,并保存执行<code>inner</code>函数的功能。</strong></p><p>我们可以看到,最终结果依次输出了<code>0</code>和<code>1</code>,说明我们的闭包是成功了的,但这样的闭包比较臃肿,我们试着提高一下,写的更加优雅一点:</p><pre class="brush:php;toolbar:false">   for (var i = 0; i <p>还可以再简化一下:</p><pre class="brush:php;toolbar:false">for (var i = 0; i <p>这样就大功告成了!</p><h2 id="总结">总结</h2><p>本篇首先介绍了闭包的定义以及不同人对闭包的理解,之后介绍了闭包产生的原因并总结了三个条件,之后举例说明了如何创建多个闭包和通过闭包实现模块,最后讲述了如何通过闭包解决for循环中使用异步函数依次输出值的问题。其实闭包没有想象的那么可怕,只要你愿意静下心去探索去了解,闭包也会对你敞开大门~</p><h2 id="写在最后">写在最后</h2><p>都看到这里了,如果觉得对你有帮助的话不妨点个赞支持一下呗~</p><p>以后会陆续更新更多文章和知识点,感兴趣的话可以关注一波~</p><p>如果哪里有错误的地方或者描述不准确的地方,也欢迎大家指出交流~</p><blockquote><p><strong>相关免费学习推荐:</strong><a href="https://www.php.cn/course/list/17.html" target="_blank" textvalue="javascript"><strong>javascript</strong></a><strong>(视频)</strong></p></blockquote>

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. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor