Details about closures in JavaScript

Source: Internet
Author: User
In JavaScript, closures are difficult to understand. In ECMAScript, the closure is defined as: closure, which refers to a function that indicates lexical representation of non-computed variables. That is to say, a function can use a variable defined outside the function. What is a closure?

In JavaScript, closures are difficult to understand. In ECMAScript, the closure is defined as: closure, which refers to a function that indicates lexical representation of non-computed variables. That is to say, a function can use a variable defined outside the function.

Is it even harder to read this definition? Don't worry. Let's analyze it.

  • A closure is a function.

  • The closure can use variables defined outside it.

  • The closure exists in the scope that defines the variable.

It seems a bit clear, but what is the meaning of variables defined outside of it? Let's take a look at the variable scope.

Variable Scope

Variables can be divided into global variables and local variables. The scope of global variables is global, and global variables can be used anywhere in js. When the var keyword is used in a function to declare a variable, the variable is a local variable. Its scope is only within the function that declares the variable, and the variable cannot be accessed outside the function.

var func = function(){    var a = 'linxin';    console.log(a);             // linxin}func();console.log(a);                 // Uncaught ReferenceError: a is not defined

The scope is relatively simple. We will not talk much about it. Let's take a look at the variable lifecycle with a relatively large relationship with the closure.

Variable Lifecycle

The life cycle of a global variable is permanent. Local variable. When the function call that defines the variable ends, the variable will be recycled and destroyed by the garbage collection mechanism. When this function is called again, a new variable is redefined.

var func = function(){    var a = 'linxin';    console.log(a);}func();

A is a local variable. After calling func, a will be destroyed.

var func = function(){    var a = 'linxin';    var func1 = function(){        a += ' a';        console.log(a);    }    return func1;}var func2 = func();func2();                        // linxin afunc2();                        // linxin a afunc2();                       // linxin a a a

It can be seen that after the first call of func2, variable a in func becomes 'linxin a' without being destroyed. At this time, func1 forms a closure, which leads to the continuation of a's lifecycle.

Here the sub-closure is clear.

  • A closure is a function, such as the above func1 function.

  • Closures use variables defined by other functions so that they are not destroyed. For example, the above func1 calls variable.

  • The closure exists in the scope that defines the variable, and variable a exists in the scope of func, so func1 must also exist in this scope.

Now we can say that the closure meets these three conditions.

Next we will use a simple and classic example to further familiarize ourselves with closures.

for (var i = 0; i < 4; i++) {    setTimeout(function () {        console.log(i)         }, 0)}

We may simply think that the console will print 0 1 2 3, but the fact is printed 4 4 4 4 4 4. Why? We found that the setTimeout function is asynchronous. When the function is executed, the for loop is over. At this time, the I value is 4, so function () {console. log (I)} finds the variable I and can only get 4.

In the previous example, the closure stores the value of the variable. Here we can also use the closure to save the value of 0 1 2 3.


for (var i = 0; i < 4; i++) {    (function (i) {        setTimeout(function () {            console.log(i)                }, 0)        })(i) }

When I = 0, 0 is passed as the parameter to the anonymous function. At this time, function (I) {} the value of I in this anonymous function is 0, when setTimeout is executed, I is directed to the outer layer, and 0 is obtained. In this loop, you can get the desired 0 1 2 3.

Memory Management

When a local variable is called in the closure, the local variable cannot be destroyed in time, which is equivalent to a global variable that will always occupy the memory. If you need to recycle the memory occupied by these variables, You can manually set the variable to null.

However, in the process of using closures, it is easier to form circular references between JavaScript objects and DOM objects, which may cause memory leakage. This is because in the garbage collection mechanism of the browser, if a circular reference is formed between two objects, they cannot be recycled.

function func() {    var test = document.getElementById('test');    test.onclick = function () {        console.log('hello world');    }    }

In the above example, the func function creates a closure using an anonymous function. The test variable is a JavaScript Object that references the DOM object whose id is test. The onclick attribute of the DOM object references the closure, and the closure can call the test variable to form a circular reference, both objects cannot be recycled. To solve this problem, you only need to set the variable in the circular reference to null.

function func() {    var test = document.getElementById('test');    test.onclick = function () {        console.log('hello world');    }    test = null;}

If you do not use an anonymous function in the func function to create a closure, but reference an external function, there will be no issue of circular reference.

function func() {    var test = document.getElementById('test');    test.onclick = funcTest;}function funcTest(){    console.log('hello world'); }

The above is a detailed description of closures in JavaScript. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.