Home Web Front-end JS Tutorial Use the most understandable code to help novices understand javascript closures. Recommended_javascript skills

Use the most understandable code to help novices understand javascript closures. Recommended_javascript skills

May 16, 2016 pm 05:55 PM

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 < 3; 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 < 3; i ) {myarr[i] = addOne(myarr[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 < 3; 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 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 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.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

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

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 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 and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

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.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

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.

See all articles