search
HomeWeb Front-endJS TutorialUse the most understandable code to help novices understand javascript closures. Recommended_javascript skills

I have recently read several articles about JavaScript closures, including the recently popular Uncle Tom series, and articles in "Javascript Advanced Programming"... I can't understand it. Some of the codes in it are from college textbooks. If you haven’t read it, it’s like a book from heaven. Fortunately, I recently came across two good books "ppk on javascript" and "object-oriented JavaScript". I am currently reading the latter. The latter does not have a Chinese version yet, but the former is still recommended to read the original version. The writing is not complicated. Friends who are interested can read it. Look, it’s suitable for friends who want to advance.
Today I will combine these two books and talk about closures in JavaScript in the simplest language and the most popular way. Since I am also a novice, please point out any mistakes. Thank you
1. Preparation Knowledge
1. Functions as parameters of functions
When learning JavaScript, you must always have a concept that is different from other languages ​​​​: function (function) is not a special thing, it is also a kind of data, and bool, string, number are no different.
The parameters of the function can be string, number, bool, such as:
function(a, b) {return a b;}
But the function can also be passed in. You heard me right, the parameters of a function are functions! Join the following two functions:

Copy the code The code is as follows:

//Place three Double the number
function multiplyByTwo(a, b, c) {
var i, ar = [];
for(i = 0; i ar [i] = arguments[i] * 2;
}
return ar;
}

Copy code The code is as follows:

//Add the number by one
function addOne(a) {
return a 1;
}

Then use
Copy the code The code is as follows:

var myarr = [] ;
//First multiply each number by two, using a loop
myarr = multiplyByTwo(10, 20, 30);
//Then add one to each number, using another Loop
for (var i = 0; i

It should be noted that this process actually uses There is still room for improvement between the two loops, so why not do this:
Copy the code The code is as follows:

function multiplyByTwo(a, b, c, addOne) {
var i, ar = [];
for(i = 0; i ar[i] = addOne (arguments[i] * 2);
}
return ar;
}

In this way, the function is passed in as a parameter, and in the first loop call directly. Such a function is the famous callback function
2. Function as return value
There can be a return value in the function, but we are generally familiar with the return of numerical values, such as
Copy code The code is as follows:

function ex(){
return 12
}

But once you realize that functions are just a kind of data, you can think of returning functions as well. Pay attention to the following function:
Copy code The code is as follows:

function a() {
alert('A!');
return function(){
alert('B!');
};
}

it returns A function that pops "B!" Next use it:
Copy the code The code is as follows:

var newFunc = a();
newFunc();

What’s the result? When a() is executed first, "A!" pops up. At this time, newFunc accepts the return value of a, a function - at this time, newFunc becomes the function returned by a. When newFunc is executed again, "B" pops up. !”
3. The scope of JavaScript
The scope of JavaScript is very special. It is based on functions, not blocks (such as a loop) like other languages. Look at the following example:
var a = 1; function f(){var b = 1; return a;}
If you try to get the value of b at this time: if you try to enter alert(b) in firebug, you will get an error Tip:
b is not defined
Why can you understand this: the programming environment or window you are in is a top-level function, like a universe, but b is just a variable in your internal function, in the universe A point on a small planet, it is difficult for you to find it, so you cannot call it in this environment; on the contrary, this internal function can call variable a, because it is exposed in the entire universe and has nowhere to hide, and it can also call b , because it's on its own planet, inside the function.
As for the above example:
Outside f(), a is visible, but b is invisible
Inside f(), a is visible, and b is also visible
A little more complicated:
Copy code The code is as follows:

var a = 1; //b,c are neither in this layer It can be seen that
function f(){
var b = 1;
function n() { //a, b, c can all call this n function, because a, b are exposed, and c is Own internal
var c = 3;
}
}

Ask you, can function b call variable c? No, remember that the scope of JavaScript is based on functions. c is inside n, so it is invisible to f.

Start formally talking about closures:

Look at this picture first:

Assume that G, F, and N represent three levels of functions respectively. The levels are as shown in the figure, and a, b, and c are the variables respectively. Based on the scope mentioned above, we have the following conclusions:

  1. If you are at point a, you cannot reference b, because b is invisible to you
  2. Only c can reference b

The paradoxical thing about closures is that the following happens:

N breaks through the limit of F! We ran to the same floor as a! Because functions only recognize the environment they are in when they are defined ( not when executed, this is very important ), c in N can still access b! At this time, a is still Unable to access b!

But how is this achieved? As follows:
Closure 1:

Copy code The code is as follows:

function f( ){
var b = "b";
return function(){ // Function without name, so it is an anonymous function
return b;
}
}

Note that the returned function can access the variable b in its parent function
If you want to get the value of b at this time, of course it is undefined
But if you do this:
Copy code The code is as follows:

var n = f();
n();

You can get the value of b! Although the n function is outside f at this time, and b is a variable inside f, there is an insider inside f, and the value of b is returned...
Now everyone has a feeling, right?
Closure 2:
Copy code The code is as follows:

var n;
function f(){
var b = "b";
n = function(){
return b;
}
}

What will happen if f is called at this time? Then a global scope function of n is generated, but it can access the inside of f and still return the value of b, which is similar to the above!
Closure 3:
You can also use closures to access the parameters of the function
Copy the code The code is as follows:

function f(arg) {
var n = function(){
return arg;
};
arg;
return n;
}

If you use:
Copy the code The code is as follows:

var m = f(123);
m();

The result is 124
Because the anonymous function returned in f has changed hands twice, first to n, and then to the outside m, but the essence has not changed. The parameters of the parent function when defined are returned
Closure 4:
Copy code The code is as follows:

var getValue, setValue;
function() {
var secret = 0;
getValue = function(){
return secret;
};
setValue = function(v){
secret = v ;
};
})

Run:
Copy code The code is as follows :

getValue()
0
setValue(123)
getValue()
123

No need to explain this, If you have a foundation in object-oriented languages ​​(such as C#), getValue and setValue here are similar to the property accessors of an object. You can assign and get values ​​through these two accessors, but not access the content
In fact, there are several examples of closures in the book, but the above four principles are enough. I hope it can serve as a starting point and give JavaScript advanced readers 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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment