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();
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);
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());
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment