search
HomeWeb Front-endJS TutorialLet you learn JS closures in minutes

Closure is an important concept in Javascript. For beginners, closure is a very abstract concept, especially the definition given by the ECMA specification. Without practical experience, it is difficult to understand it from the definition. Therefore, this article will not describe the concept of closure in a long way, but will go directly to the practical information so that you can learn closure in minutes!

1 Closures at a glance

When I come into contact with a new technology, the first thing I do is to find its demo code. For us, looking at code can better understand the essence of a thing than natural language. In fact, closures are everywhere. For example, the core codes of jQuery and zepto are all included in a large closure, so I will write the simplest and most primitive closure first so that you can generate closures in your brain. Picture:

function A(){    function B(){
       console.log("Hello Closure!");
    }    return B;
}var C = A();
C();//Hello Closure!

This is the simplest closure.

After having a preliminary understanding, let’s briefly analyze how it is different from ordinary functions. The above code is translated into natural language as follows:

(1) Define ordinary function A

(2) Define the ordinary function B

in A (3) Return B

in A (4) Execute A, and assign the return result of A to the variable C

( 5) Execute C

Summarize these 5 steps into one sentence:

The internal function B of function A is referenced by a variable c outside function A.

Reprocess this sentence and it becomes the definition of closure:

When an internal function is referenced by a variable outside its external function, it A closure is formed.

So, when you perform the above 5 steps, you have already defined a closure!

This is closure.

2 The purpose of closure

Before understanding the function of closure, let’s first understand the GC mechanism in Javascript:

In Javascript, if an object is no longer referenced, then the object will be recycled by GC, otherwise the object will always be saved in memory.

In the above example, B is defined in A, so B depends on A, and the external variable C refers to B, so A is indirectly referenced by C.

In other words, A will not be recycled by GC and will always be stored in memory. In order to prove our reasoning, the above example is slightly improved:

function A(){    var count = 0;    function B(){
       count ++;
       console.log(count);
    }    return B;
}var C = A();
C();// 1C();// 2C();// 3

When we need to define some variables in the module and want these variables to be kept in memory When it is in the module but will not "pollute" the global variables, you can use closures to define this module.

3 High-end writing method

The above writing method is actually the most primitive writing method, but in actual applications, closures and anonymous functions will be used together. The following is a commonly used way to write a closure:

(function(document){    var viewport;    var obj = {
        init:function(id){
           viewport = document.querySelector("#"+id);
        },
        addChild:function(child){
            viewport.appendChild(child);
        },
        removeChild:function(child){
            viewport.removeChild(child);
        }
    }
    window.jView = obj;
})(document);

The function of this component is to initialize a container, and then you can add sub-containers to the container or remove a container.

The function is very simple, but another concept is involved here: executing the function immediately. A brief understanding is enough. What needs to be understood is how this writing method implements the closure function.

The above code can be split into two parts: (function(){}) and (), the first () is an expression, and this expression itself is an anonymous function, so add () after this expression. Indicates the execution of this anonymous function.

So the execution process of this code can be decomposed as follows:

var f = function(document){    var viewport;    var obj = {
        init:function(id){
            viewport = document.querySelector("#"+id);
        },
        addChild:function(child){
            viewport.appendChild(child);
        },
        removeChild:function(child){
            viewport.removeChild(child);
        }
    }
    window.jView = obj;
};
f(document);

It seems that the shadow of closure is seen in this code, but there is no return value in f , it seems that it does not meet the conditions for closure. Pay attention to this code:

window.jView = obj;

obj is an object defined in function f. This object defines a series of methods to execute window. jView = obj defines a variable jView in the window global object and points this variable to the obj object, that is, the global variable jView refers to obj. And the function in the obj object refers to the variable viewport in function f, so in function f The viewport will not be recycled by GC, and the viewport will always be saved in memory, so this writing method meets the conditions of closure.

4 Simple summary

This is the simplest understanding of closure. Of course, closure has a deeper understanding, which is much more involved. , you need to understand the execution context, activation object, and operating mechanism of scope and scope chain of JS. But as a beginner, you don’t need to understand these for now. After you have a simple understanding, you must use it in actual projects. When you use it more, you will naturally have a deeper understanding of closures!

Statement
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
一文浅析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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)