Easy to understand JavaScript closures

Source: Internet
Author: User
Tags closure

Summary

The closure mechanism is the key and difficult point of JavaScript, this article hopes to help everyone to learn the closure easily

One, what is closures?

Closures are functions that can access variables in another function scope.
The following is a list of common closure implementations, with examples explaining closure concepts

 function f1 (var n=999; Nadd=function (1} function f2 (    Span class= "Hljs-params") {alert (n);  } return F2;  } var result=f1 (); Result ();  //999 nadd (); Result (); //            

F1 is the parent function of F2, and F2 is assigned to a global variable (return value), which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends. This forms a closure.
So it can be understood that way. The closure mechanism is that if a function references a variable of another function B, but B returns after a still does not return, still exists, because the reference of a, so all the local variables of B will not log out with B, will persist until a logoff. At this point a is the closure.

Second, closure of the This pointer

Closures are usually called in the global environment, so this usually points to the window, depending on the execution environment, in summary this points to the execution environment.
If the this of the closure is to point to the enclosing object of the closure, you need to pass the this of the containing object as a variable into the closure.

Iii. note points for using closures
    1. Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function.

    2. The closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, and the closure as its public method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the inner variable of the parent function.

Iv. solving a common face problem of a closure package

Problem:

 function onmyload (/* throws the question: the goal of this question is to want to pop up the corresponding digital subscript each time you click on the target. 0~4, but the reality is that no matter which target you click, the number 5 pops up: The onclick of each item in ARR is a function instance (function object), and this instance of the function also produces a closure field that references the variables of the outer closure field, whose function Scope's Closure object has a reference named I, the contents of the private variables of the outer closure domain change, the value of the internal closure field will change naturally. */var arr = document.getelementsbytagname (" P "); for (var i = 0; i < arr.length;i++ {Arr[i].onclick = function (

Workaround
1, add a layer of function outside, I as a function parameter passed in, so that every time you save the function inside the variable, and the external I is not the same memory space, and each call to the function will generate a local variable, so you can guarantee that each saved value does not affect each other.

for(var i = 0; i<arr.length;i++){    arr[i].onclick = (function(arg){ return function () { alert(arg); } })(i);}

2, with ES6 New Let, the For-loop var i is changed to let I, so that the current I only in this cycle is valid, so each cycle of I is actually a new variable. You may ask, if the variable I of each cycle is re-declared, how does it know the value of the previous cycle, thus calculating the value of this round? This is because the JavaScript engine internally remembers the value of the last loop, and when it initializes the variable I of this round, it is calculated on the basis of the previous cycle.

Easy to understand JavaScript closures

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.