search
HomeWeb Front-endJS TutorialWhat is a closure? Let's talk about closures in JavaScript and see what functions they have?

What is closure? See what closures do? The following article will talk about closures in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

What is a closure? Let's talk about closures in JavaScript and see what functions they have?

In the process of front-end learning, we will inevitably encounter many problems, so today we will talk about two problems from the perspective of a beginner:

What is a closure?

What are the functions of closures?

In fact, closures are everywhere when we learn javascript, you just need to be able to recognize and accept it. Closures are not a tool that requires learning a new syntax or pattern to use. Closures are a natural consequence of writing code based on lexical scope. We rarely need to intentionally create closures when writing code.

I believe that many friends are already muttering in their hearts, what is this lexical scope? Don’t panic, just listen to me slowly. In short, lexical scope is defined in lexical scope. scope of the stage. In other words, lexical scope is determined by where you place variables and block-level scopes when you write your code, so the scope remains unchanged when the lexical analyzer processes the code (most of the time) . ——"JavaScript Volume You Don't Know"

Let's take an example first

function test(){
   var arr = []
   for(var i=0;i<blockquote><p>Let's analyze this code first:
When this code is executed, according to common sense analysis, ten numbers from 0 to 9 should be printed out in sequence; but the for loop does not take time to run (neglected in microseconds). When the function test returns arr, arr[ ] Inside are 10 function(){console.log(i);}. At this time, the functions in the array are not executed. When var myArr = test() calls the test function, since the execution time of the for loop is ignored, this At this time, i is already 10, so 10 10s are printed. </p></blockquote><p>I believe someone will ask at this time, what does this have to do with the closure we are going to talk about? So what if we slightly modify this code and change it into an accumulator? To realize him? </p><blockquote>
<p>I believe there will be big shots at this time saying that isn’t that simple? </p>
<p>Change the var definition to a let definition so that the first for loop becomes a block-level scope, then it can become an accumulator. Of course there is no problem, </p>
</blockquote><p> But what we are talking about today is how to implement an accumulator in ES5. Then let's take a look at the following code: </p><pre class="brush:php;toolbar:false">function test(){
    var arr = []
    for(var i=0;i<p> Careful friends will definitely find that this is changing the function body in the loop into a self-executing function, but the output result at this time is
Ten numbers are output from 0 to 9 in sequence, which contains closures. When we start executing this code, the second for loop will be called ten times. When each self-executing function is executed, a self-executing function will be created. The AO object of the executing function. There is an attribute named j in the AO object of the self-executing function. Normally, after the execution of the self-executing function, its AO object should be destroyed, but when myarr[j] ( ) is executed, the attribute name j is searched for in the AO object of arr[j] at the top of the scope chain, but it is not found. Then, we search down the scope chain and find it in the AO object of the self-executing function, so when the self-executing function When the execution function ends, its AO object will not be recycled by the garbage collection mechanism, otherwise an error will be reported when myarr[j] () is executed, and a closure will be formed at this time. </p><h3 id="strong-When-a-function-is-saved-externally-a-closure-will-be-generated-strong"><strong>When a function is saved externally, a closure will be generated</strong></h3><p>Let’s give another example</p><pre class="brush:php;toolbar:false">function a(){
    function b(){
        var bbb = 234
        console.log(aaa);
    }
    var aaa = 123
    return b // b出生在a里面,但是被保存出去了
}

var glob = 100
var demo = a()
demo()

In this code we First, use precompilation to analyze. First, define a global GO object. Find the global declaration and find the global variable declaration. Use the variable declaration as the attribute name of GO and the value is undefined. Find the function declaration globally and use the function name as The attribute name of the GO object, and the value is assigned to the function body. At this time it should be GO{ glob: undefined--->100; demo: undefined; a: fa(){} }; Then create an AO{ aaa: undefined--->123;b: fb(){} } for function a, and finally precompile function b in function a to create an AO{ b: undefined-- ->234};The order of the scope chain at this time is 1. AO object of function b; 2. AO object of function a; 3. Global GO object. When we print aaa in function b, we start from the top of the scope chain. If there is no aaa in the AO object of function b, we will search down along the scope chain to find the AO of the second-level function a. The object is to find the value of aaa as 123 and output the result.

如果我们没有从预编译的角度去分析就会认为此时的aaa应该会报错的,当var demo = a()执行时,当a函数执行结束,那么a对应的AO对象应该被销毁了,照常理分析当我们执行demo时作用域链此时应该会创建b的AO对象和GO对象,此时只有b的AO对象,没有a的AO对象,应该不能打印出aaa的值,但是此时aaa的值为123,则说明a的AO对象没有被销毁,那么为什么呢?原因就在于这里创建了闭包,当var demo = a()执行结束之后,垃圾回收机制会来问,a函数老兄,我看你都执行完毕了,你的运行内存是不是可以给我释放了,但是此时a函数只能无奈摇摇头说道,老哥,我也不确定我有没有执行完毕,我执行完创建了一个b,但是b又不归我管,所以我也不确定b有没有被调用,所以我也不确定我有没有执行完毕,垃圾回收机制想了想,既然你都不知道那我就不回收了,要是回收了还没执行完的就该报错了,所以此时a的AO对象就没有被回收。

补充全面一点就是:当一个函数内部的函数被保存到函数外部时,就会产生闭包。

相信通过这两个例子,你已经对闭包有了一个大概的了解,那接下来我们说一下闭包有哪些作用。

闭包的作用

    1. 实现公有变量 例如:累加器(3.js)
    1. 做缓存
    1. 可以实现封装,属性私有化
    1. 模块化开发,防止污染全局变量

我们对闭包的作用也来一个例子(3.js)

 var count = 0
 function add() {
   return count++
 }
 console.log(add());
 console.log(add());
 console.log(add());

 这是一段比较普通的累加的代码,但是如果我们在实习甚至是工作的时,公司要求你把累加器封装成一个模块化的代码,那么
 此时,为了模块化我们尽可能避免定义全局变量,但是不定义全局变量我们如何实现呢,此时我们就可以用到闭包了;

function add() {
    var count = 0
    function a() {
      ++count
      console.log(count);
    }
    return a
  }
  var res = add()
  res()
  res()
  
  //add函数结束之后,add的AO对象没有被销毁,因为add函数执行完了之后,返回的a不知道是否被调用就形成了闭包,这样
  就能使得不使用全局变量也能封装成一个模块化的累加器。

结语

那么关于闭包以及闭包的作用相关的一些个人见解就是这些,目前对于闭包也只是一些浅显的了解,后期学习之后完善过后会出后续关于闭包的相关文章,感谢您的观看,欢迎批评斧正,一起共同进步。

【相关推荐:javascript视频教程web前端

The above is the detailed content of What is a closure? Let's talk about closures in JavaScript and see what functions they have?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
一文浅析Golang中的闭包一文浅析Golang中的闭包Nov 21, 2022 pm 08:36 PM

闭包(closure)是一个函数以及其捆绑的周边环境状态(lexical environment,词法环境)的引用的组合。 换而言之,闭包让开发者可以从内部函数访问外部函数的作用域。 闭包会随着函数的创建而被同时创建。

python闭包有哪些python闭包有哪些Oct 30, 2023 pm 04:53 PM

python闭包主要包括函数闭包和装饰器闭包。详细介绍:1、函数闭包是指在一个函数内部返回另一个函数,并且返回的函数能够访问到其内部变量。这样的返回函数就是函数闭包,函数闭包在程序中可以被反复使用,因此可以用来实现一些功能上的封装;2、装饰器闭包是指在使用装饰器时,被装饰的函数并没有直接被调用,而是被包装在一个函数内部,并返回一个新的函数。这个新的函数就是一个装饰器闭包等等。

如何利用PHP7的匿名函数和闭包实现更加灵活的代码逻辑处理?如何利用PHP7的匿名函数和闭包实现更加灵活的代码逻辑处理?Oct 21, 2023 am 10:21 AM

如何利用PHP7的匿名函数和闭包实现更加灵活的代码逻辑处理?在PHP7之前,我们经常使用函数来封装一段特定的逻辑,然后在代码中调用这些函数来实现特定的功能。然而,有时候我们可能需要在代码中定义一些临时的逻辑块,这些逻辑块没有必要创建一个独立的函数,同时又不想在代码中引入太多的全局变量。PHP7引入了匿名函数和闭包,可以很好地解决这个问题。匿名函数是一种没有名

Python中的闭包是如何实现的?Python中的闭包是如何实现的?Oct 21, 2023 am 10:33 AM

Python中的闭包是如何实现的?闭包是一种函数内部定义的函数,并且在函数内部引用了外部函数的变量。这种特性使得内部函数可以访问外部函数的变量,并且在外部函数执行完毕后,闭包仍然可以访问和操作外部函数的变量。闭包在Python中通过以下几个步骤来实现:定义外部函数,并在其中定义内部函数:首先,我们需要在外部函数内部定义一个内部函数。这个内部函数即是闭包。de

怎么样减少闭包的产生怎么样减少闭包的产生Oct 27, 2023 pm 04:28 PM

减少闭包产生的方法有避免不必要的闭包、控制闭包的返回值、使用弱引用、减少不必要的全局变量、合理使用循环和递归、使用事件代理、编写单元测试、遵循设计原则和使用工具进行代码分析等。详细介绍:1、避免不必要的闭包,在很多情况下,闭包并非必需的,可以用模块模式来实现私有变量,避免使用闭包;2、控制闭包的返回值,在使用闭包时,应该尽量控制闭包的返回值,如果闭包返回的是基本数据类型等等。

react有哪些闭包react有哪些闭包Oct 27, 2023 pm 03:11 PM

react有事件处理函数、useEffect和useCallback、高阶组件等等闭包。详细介绍:1、事件处理函数闭包:在React中,当我们在组件中定义一个事件处理函数时,该函数会形成一个闭包,可以访问组件作用域内的状态和属性。这样可以在事件处理函数中使用组件的状态和属性,实现交互逻辑;2、useEffect和useCallback中的闭包等等。

如何使用PHP7的匿名函数和闭包实现更加灵活和可复用的代码逻辑?如何使用PHP7的匿名函数和闭包实现更加灵活和可复用的代码逻辑?Oct 24, 2023 am 10:30 AM

如何使用PHP7的匿名函数和闭包实现更加灵活和可复用的代码逻辑?在PHP编程领域中,匿名函数和闭包是非常有价值和强大的工具。PHP7引入了一些新的语言特性,使得使用匿名函数和闭包更加方便和灵活。本文将介绍如何使用PHP7的匿名函数和闭包来实现更加灵活和可复用的代码逻辑,并提供一些具体的代码示例。一、匿名函数匿名函数是一种没有名称的函数。在PHP中,可以将匿名

如何解决Python的闭包错误?如何解决Python的闭包错误?Jun 24, 2023 pm 11:23 PM

Python是一种非常流行的编程语言,因为它非常易学易用,同时也具备了强大的功能。其中,闭包是Python中的一种函数,它可以在函数的内部定义另一个函数,并返回这个函数作为函数的返回值。尽管闭包非常方便,但有时会出现某些错误,比如闭包错误。本文将介绍如何解决Python的闭包错误。初步了解闭包在Python中,闭包是由一个内部函数和一个定义在内部函数之外的函

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools