Home Web Front-end JS Tutorial Detailed explanation of closures in Javascript

Detailed explanation of closures in Javascript

Mar 12, 2017 am 11:22 AM

This article explains in detail the closure in Javascript

1. Closure! ?

 Closure (closure) is a difficulty in the Javascript language. It is not easy for beginners to understand, so let’s first take a look at the meaning of closure.

Baidu Encyclopedia and "official" explanation: The so-called "closure" refers to a variable that has many variables and binds these The expression of the variable's environment (usually a function), so these variables are also part of the expression.

Wikipedia: In programming languages, closures (also known as lexical closures or functional closures) are used in A technique for implementing lexically scoped name binding in languages ​​with first-class functions.

However, we see that these official explanations do not clearly understand what the hell closure is. They only have a question mark, "What are you talking about?" ?”.

In fact, closure is simply a function that can read the local variables defined inside the function, while in Javascript there are only sub-functions inside the function Only local variables can be read, so we can also understand closures as functions defined inside functions.

2. Function variables

If we want to understand closures, we must first understand the variables in the function. These variables have their own scope. What is scope? Now, generally speaking, the name used in a piece of program code is not always valid/available, and the code scope that limits the availability of the name is the scope of the name.

 The scope of variablesThere are two types, one is global and the other is local, which is what we call global variables and local variable.  


var a=50;function fun1(){
    alert(a);
}
fun();
Copy after login


In the above code, a is defined outside the function, so it is inside the function Calling variable a can naturally read its value. We call a here a global variable.


function fun2(){
    var a=50;
}
alert(a);
Copy after login


In this code, we define a inside the function, then when a is called outside the function, it An error will be reported, telling you "a is not defined", we can't find a? Have we defined a? Of course it has been defined! It's just that it's a local variable.

3. How to find the variables "hidden" in the function

When we type the keyboard code, there are always some reasons that require us to get the inside of the function local variables, then we need to use a method to extract the local variables "hidden" in the function.

That is, inside the function, we define another function.


function fun3(){
    var a=50;
    function fun4(){
        return a;
    }
    return fun4();
}
//console.log(a); 报错
console.log(fun3());
Copy after login


In the above code, we define a variable a in fun3, so that we call a outside the function fun3 It will also report an error that it cannot be found. For function fun4 inside function fun3, a can be called, so external a is outside function fun4. On the contrary, if a variable is defined in fun4, then fun3 cannot be called.

Another concept is involved here, which is chain scope, which is what we call scope chain. The scope chain means that the same variable name will generate a scope chain. When accessing the variable name, it will first find whether the current scope contains the variable. If not, it will go to the parent scope to find it. Until the global variable is finally found, if the global variable cannot find the variable, an error will be reported.

Then if you want to call variable a outside function fun3, you must define another function fun4 inside function fun3. We let it return the variable a that it can call, then function fun4 The result is variable a, then we return function fun4, then we execute function fun3, and the result is the value of variable a.

To put it simply, as long as fun4 is used as the return value, we can read its internal variables outside fun3.

4. What should we pay attention to when calling local variables (using closures)?

 1. Closures will cause the variables in the function to be stored in memory, which consumes a lot of memory, so closures cannot be abused, otherwise the performance of the web page will be reduced.

 2. Do not change the value of the internal variable of the parent function casually.


Finally, to summarize, a closure is a function that can read the internal variables of other functions. It allows us to call variables in the parent function outside the parent function. There is code It is actually not difficult to understand under the circumstances. The important thing is that in unpredictable code, the specific application of closure still requires us to truly understand it before we can apply it skillfully.

 


The above is the detailed content of Detailed explanation of closures in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles