Home Web Front-end JS Tutorial Understand and use JavaScript's closure mechanism_Basic knowledge

Understand and use JavaScript's closure mechanism_Basic knowledge

May 16, 2016 pm 03:45 PM
javascript Closure

The great Comrade Einstein once said: "If you can't explain something clearly to a 6-year-old child, then you don't understand it yourself." However, when I explained what closures were to a 27-year-old friend, I failed completely.

This was originally a question raised by a foreign friend on Stack Overflow about JavaScript closures. However, since this question was asked on Stack Overflow, of course many experts will come out to answer it. Some of the answers are indeed classics, such as the following one:

If you define an internal function in an external function, that is, a function nested function, then the internal function can also access the variables in the external function:

function foo(x) {
 var tmp = 3;
 function bar(y) {
 alert(x + y + (++tmp));
 }
 bar(10);
}

foo(2); // alert 16
foo(2); // alert 16
foo(2); // alert 16

Copy after login

This code can be executed correctly and returns the result: 16, because bar can access the variable tmp of the external function and can also access the parameter x of the external function foo. But the above example is not a closure!

To implement closure, the internal function needs to be returned as the return value of the external function. Before returning, the internal function will lock all the variables in the external function that have been accessed in the memory. In other words, these variables It will reside in the memory of bar and will not be recycled by the garbage collector, as follows:

function foo(x) {
 var tmp = 3;
 return function (y) {
 alert(x + y + (++tmp));
 }
}
var bar = foo(2); // bar 现在是个闭包了
bar(10); // alert 16
bar(10); // alert 17
bar(10); // alert 18

Copy after login

In the above code, when bar is executed for the first time, the result will still be returned: 16, because bar can still access x and tmp, although it no longer directly exists in the scope of foo. So since tmp is locked in the closure of bar, tmp will be incremented every time bar is executed, so when bar is executed for the second and third times, 17 and 18 are returned respectively.

In this example, x is just a pure value. When foo is called, the value x will be copied to foo as a parameter.

But when JavaScript handles objects, it always uses references. If you call foo with an object as a parameter, then what is passed in foo is actually a reference to the original object, so the original object is also equivalent to being closed. , as follows:

function foo(x) {
 var tmp = 3;
 return function (y) {
 alert(x + y + tmp++);
 x.memb = x.memb ? x.memb + 1 : 1;
 alert(x.memb);
 }
}
var age = new Number(2);
var bar = foo(age); // bar 现在是个闭包了
bar(10); // alert 15 1
bar(10); // alert 16 2
bar(10); // alert 17 3

Copy after login

As expected, every time bar(10) is executed, not only tmp is incremented, but x.memb is also incremented, because x in the function body and age outside the function refer to the same object.

via http://stackoverflow.com/questions/111102/how-do-javascript-closures-work

Supplement: Through the above examples, you should be able to understand closures more clearly. If you think you understand it, you can try to guess the execution result of the following code:

function foo(x) {
 var tmp = 3;
 return function (y) {
 alert(x + y + tmp++);
 x.memb = x.memb ? x.memb + 1 : 1;
 alert(x.memb);
 }
}
var age = new Number(2);
var bar1 = foo(age); // bar1 现在是个闭包了
bar1(10); // alert 15 1
bar1(10); // alert 16 2
bar1(10); // alert 17 3

var bar2 = foo(age); // bar2 现在也是个闭包了
bar2(10); // alert ? ?
bar2(10); // alert ? ?
bar2(10); // alert ? ?

bar1(10); // alert ? ?
bar1(10); // alert ? ?
bar1(10); // alert ? ?

Copy after login

When used in practice, closures can create very elegant designs, allowing customization of the various calculation methods defined on funarg. The following is an example of array sorting, which accepts a sorting condition function as a parameter:

[1, 2, 3].sort(function (a, b) {
 ... // 排序条件
});
Copy after login

The same example is that the map method of an array maps the original array to a new array based on the conditions defined in the function:

[1, 2, 3].map(function (element) {
 return element * 2;
}); // [2, 4, 6]
Copy after login

Using functional parameters, you can easily implement a search method and support unlimited search conditions:

someCollection.find(function (element) {
 return element.someProperty == 'searchCondition';
});
Copy after login

There are also application functions, such as the common forEach method, which applies the function to each array element:

[1, 2, 3].forEach(function (element) {
 if (element % 2 != 0) {
  alert(element);
 }
}); // 1, 3
Copy after login

By the way, the apply and call methods of function objects can also be used as application functions in functional programming. Here, we think of them as application functions - functions applied to parameters (in apply it is the parameter list, in call it is an independent parameter):

(function () {
 alert([].join.call(arguments, ';')); // 1;2;3
}).apply(this, [1, 2, 3]);
Copy after login

Closures have another very important application - delayed calling:

var a = 10;
setTimeout(function () {
 alert(a); // 10, after one second
}, 1000);
还有回调函数:

//...
var x = 10;
// only for example
xmlHttpRequestObject.onreadystatechange = function () {
 // 当数据就绪的时候,才会调用;
 // 这里,不论是在哪个上下文中创建
 // 此时变量“x”的值已经存在了
 alert(x); // 10
};
//...

Copy after login

You can also create encapsulating scopes to hide helper objects:

var foo = {};

// 初始化
(function (object) {

 var x = 10;

 object.getX = function _getX() {
  return x;
 };

})(foo);

alert(foo.getX()); // 获得闭包 "x" – 10

Copy after login

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

The impact of function pointers and closures on Golang performance The impact of function pointers and closures on Golang performance Apr 15, 2024 am 10:36 AM

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

How are closures implemented in Java? How are closures implemented in Java? May 03, 2024 pm 12:48 PM

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

Summary of the advantages and disadvantages of golang anonymous functions and closures Summary of the advantages and disadvantages of golang anonymous functions and closures May 05, 2024 am 09:54 AM

Anonymous functions are concise and anonymous, but have poor readability and are difficult to debug; closures can encapsulate data and manage state, but may cause memory consumption and circular references. Practical case: Anonymous functions can be used for simple numerical processing, and closures can implement state management.

See all articles