All those years we've been together JS closures, scopes, this, let's draw a perfect full stop together.

Source: Internet
Author: User

Before have written the closure, scope, this aspect of the article, but now think about what was written at that time is too much nonsense, so that around around, so that the novice is more difficult to understand, so there is this article, good and closed, scope, this is over.

First question: What is a closure?

I don't want to answer that question, but I can tell you that the closure solves the problem that the function's internal variables cannot be accessed outside the functions . Here is a section of code that does not use closures:

function fn () {

var a = 10;

}

alert (a);

Error, because A is undefined, although the function FN defines a but it can only be used in the function fn. That is, the scope of the problem.

Look at the ' closure can solve the function of the outside of the function cannot access the internal variables of the problem ' this paragraph, as if a bit of meaning, then how the closure is done, see the code below.

function fn () {

Defines a variable name

var name = ' Chasing the dream ';

What do I do if I want to access this variable outside of the name now? HA: There is no return, I return it, I will use a variable to receive it, haha haha ~~~~~

return name;

}

var name = FN ();//receives the name value that FN returns.

alert (name);//Chase dream Son;

Original The so-called closure is the return of the function, but it doesn't seem that magical, right? In fact, closures also have a very important feature. Take a look at an example.

var lis= document.getelementsbytagname[' Li '];

If the lis.length in this code = 5;

for (Var i=0;i<lis.length;i++) {

Lis[i].onclick = function () {

alert (i);

};

}

The end result is that no matter which Li element is clicked, it is 4. Don't believe you try. Why is it. See below for analysis.

    

for (Var i=0;i<lis.length;i++) {

}

i = 4, right?

Lis[0].onclick = function () {

alert (i);

};

Lis[1].onclick = function () {

alert (i);

};

Lis[2].onclick = function () {

alert (i);

};

Lis[3].onclick = function () {

alert (i);

};

Lis[4].onclick = function () {

alert (i);

};

Why is this, because your for loop just gives Li a bind event, but the function code inside does not execute AH, this execution is executed when you click, OK? But at this point I is already 4, so all of them print out 4来.

If we want to solve this problem we can use closures, the characteristics of the closure is not just to let the function external access function internal variables so simple, there is a big feature is that through the closure we can let the variables in the function persist. View

function fn () {

var num = 0;

return function () {

Num+=1;

alert (num);

};

}

var f = fn ();

f (); 1

f (); 2

If you're a beginner, you probably don't think it has anything. OK, let you see something.

function fn () {

var num = 5;

Num+=1;

alert (num);

}

FN (); 6

FN (); 6

Why is it? Because once the function is called inside the content will be destroyed, the next call is a new function, and the previous call is irrelevant, but there is a special case, see this:

  

function fn () {

var num = 0;

return function () {

Num+=1;

alert (num);

};

}

var f = fn ();

f (); 1

f (); 2

This code is very simple, do not be deceived by it, our home page defines an FN function, in which a num defaults to 0, and then returns an anonymous function (that is, a function without a name). We receive this return function externally with F. What this anonymous function does is add num 1 and the alert we use to debug.

Here the reason to play this function num is not destroyed because of the problem of the anonymous function, because this anonymous function uses this num, so it is not destroyed, has been kept in memory, so we f () when NUM can be added.

Here you can not understand, the reason for this feeling is because JS recycling mechanism you do not understand, it is strongly recommended that you look at my previous explanation of JS in the recycling mechanism is the same thing. This article.

The knowledge about closures is here, if you want to see the case of closures can see this: from the closure case study of the role of closures, will not be by you.

Out: About binding an event in a for loop the print variable i is the last time.

The scope of the above has already been finished ~ ~ ~

Big Front 369451410 welcome you to join.

Just say this:

We often use this, but maybe you don't know what it is, do you?

Lis[i].onclick=function () {this.style.border= "1px solid #ccc";};

This represents lis[?] It's a reference.

Here I is not I is actually an accurate number: such as Lis[2].onclick = function () {this.style.border= "1px solid #ccc";}; this = lis[2];

To put it simply, this is always referencing an object.

Lis[2] It is also an object, which is a HtmlElement object.

In fact, no matter what circumstances it will have the object, this you do not have to worry about, see

function fn () {

THIS.name = "Chasing the Dream Son";

};

FN ();

alert (this.name);//Chase Dream Son

Of course it can.

alert (name);

Although there seems to be no object in this code, it is a big mistake because the browser environment has a window object by default, so you can actually use the this.name in the function to represent the window.

var json = {

Name: ' yyy ',

Fn:function () {alert (this.name)}

};

Json.fn (); yyy

fn belongs to JSON, so this is actually json.

If you are a beginner to suggest that you remember these three points for the time being, of course this has a lot to say, but as a beginner you can use Console.log in the project to check if this is what you expect.

More about this content, you can see a thorough understanding of JS in the direction of this, do not have to hard back.

This article is not an introductory tutorial, this article is mainly to summarize the previous not understanding of the place, or in a more simple and clear way to write, of course, according to my own understanding, not necessarily you can understand, sorry, all right from here to end it.

All those years we've been together JS closures, scopes, this, let's draw a perfect full stop together.

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.