javascript--to understand closures in a simple way

Source: Internet
Author: User
Tags object closure log modify variables return variable access

Closures have been heard in the first contact with JavaScript. The first thing to be clear is that it does not understand complexity, and it is very useful. So what are the basics before we get to know about closures? I personally think that the most important is the scope (lexical scope), if the scope and scope chain of the students do not understand the best to learn first, and then back to understand the closure, it is more relaxed.

The following goes directly to the subject.

We know that a function is scoped, and local variables defined within the function are accessible only within the function. Once the function access is destroyed, the local variables are destroyed, and the local variables cannot be accessed again in any way, except for closures. That is, we can access the variables inside the function from the outside of the function by means of a closure, even if that function has been destroyed. Yes, the most important use of closures is that we provide only certain interfaces to access and modify local variables, while external access to local variables is not directly available.

Having said so much about how to use closures, let's look at what a closure looks like. Again to the point of raising a chestnut, still is the simplest people and name.

var people = function () {        var name = "Yika";      & nbsp;  var sayname = function () {            return name;  //access to the People function local variable name        }          var setname = function (newName) {            name = newname; //accessed the People function's local variable name        }          return{            Sayname:sayname,              Setname:setname         }//returns an object    }     var p1 = people ();       & nbsp The function return is an object that has two functions sayname and SetName     Console.log (p1.name;    //undefined.   name is the local variable in the people function, not the P1 object's properties, of course, undefined      Console.log (P1.sayname ());//"Yika"     p1.setname ("Ruyi");       //Modify the value of the local variable name by the SetName function     Console.log (P1.sayname ());/"Ruyi"

After reading this example, we must have an understanding of how many closures, in addition to the content of the comments, the following to make some additions.

Q: Why is the local variable Name property not destroyed after the people is executed, but the value is also saved in memory.

A: In the example, the function annotation is written specifically (accessing the local variable name of the People function). It is because the Sayname function and the SetName function in the People function access the Name property and pass the return to the P1 object, which is the two method of P1. Because the method always references the local variable of the people function, it is not eliminated and is still in memory. This creates a closure that allows access to local variables within the function outside the function.

In this respect, we can change a more intuitive wording.

var people = function () {
var name = ' Yika ';

var obj = {
sayname:function () {return
name;
},
setname:function (newName) {
name = NewName
}}
;

return obj; Intuitive return Object
}
//The following results are the same.

Of course, closures are not always easy to use, especially in the cycle. Continue to cite examples

           nbsp;                            

When we run the above code, we think about it, loop through the button and output the number of the button, but we get 7 forever. In fact, with the closure we talked about will let the value of the variable has been stored in the memory of the principle to think about it, you should understand. When we loop the button click event, it refers to the I variable in the for loop. When all the buttons are bound to the Click event, the value of I has become 7, of course, all the button output is 7! How to solve this problem is also very good to do, but I hope to stay for you to think. Here's a general idea, we can create an auxiliary function outside of the loop and let the auxiliary function return a function that binds the current I.

Of course, here I also just a brief introduction of the closure of the package, I hope you can help us simple and easy to understand the closure of the package.



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.