Easy understanding of JavaScript closures

Source: Internet
Author: User
The closure mechanism is the focus and difficulty of JavaScript. This article hopes to help you easily learn the closure. Next let's take a look at the closure mechanism as the key and difficulty of JavaScript. This article hopes to help you easily learn the closure. Let's take a look at it with the small Editor.

Summary

The closure mechanism is the focus and difficulty of Javascript. This article hopes to help you easily learn the closure.

1. What is a closure?

A closure is a function that can access variables in another function scope.

The following describes the common closure implementation methods.

function f1(){    var n=999;    nAdd=function(){n+=1}    function f2(){      alert(n);    }    return f2;  }  var result=f1();  result(); // 999  nAdd();  result(); // 1000

F1 is the parent function of f2, and f2 is assigned a global variable (return value), which causes f2 to always be in the memory, while f2 depends on f1, therefore, f1 is always in the memory and will not be recycled by the garbage collection mechanism after the call is completed, which forms a closure.

Therefore, we can understand this.The closure mechanism is that if function A references the variable of function B of another function, but function A does not return the result after function B returns the result, it still exists because of reference of function, therefore, all local variables of B are not logged out with B's exit, and will exist until A logs out. In this case, A is the closure.

2. this pointer of the Closure

Closures are usually called in the global environment, so this usually points to the window. The actual situation still needs to be determined by the execution environment. In short, this points to the execution environment.

If you want this of the closure to point to the included object of the closure, you need to pass this containing object as a variable into the closure.

3. Notes for using closures

  1. Because the closure will make the variables in the function be stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause the performance of the web page, and may cause memory leakage in IE. The solution is to delete all unused local variables before exiting the function.

  2. The closure changes the value of the internal variable of the parent function outside the parent function. Therefore, if you use the parent function as an object, use the closure as its Public Method, and use internal variables as its private value ), be sure not to change the value of the internal variable of the parent function.

4. Solve a closure FAQ

Problem:

Function onMyLoad () {/* throws a problem: the objective of this question is to pop up the corresponding number subscript 0 ~ each time you click the target ~ 4. However, no matter which target you click, the number 5 is displayed. The onclick of each item in arr is a Function instance (Function object ), this function instance also generates a closure field, which references variables in the external closure field. The function scope closure object has a reference named I, the private variable content of the external closure field changes, and the value of the internal closure field naturally changes */var arr = document. getElementsByTagName ("p"); for (var I = 0; I <arr. length; I ++) {arr [I]. onclick = function () {alert (I );}}}

Solution

1. Add a function outside and pass I as a function parameter. In this way, each time the variable inside the function is saved, it is not the same memory space as the external I, each time a function is called, a local variable is generated. Therefore, each stored value does not affect each other.

For (var I = 0; I

2. Use the New let in ES6 to change the var I of the for loop to let I, so that the current I is only valid in this round of loop. Therefore, the I of each loop is actually a new variable. You may ask, if the variable I in each loop is re-declared, how does it know the value of the previous loop to calculate the value of this round of loop? This is because the Javascript engine remembers the value of the previous loop. When initializing the variable I of this round, it calculates the value based on the previous loop.

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

Related Article

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.