JavaScript Learning Notes function chapter (iii): Closures and References _ basics

Source: Internet
Author: User
Tags anonymous closure

One of the most important features of Javascript is the use of closures. Because of closures, the current scope always has access to external scopes. Because Javascript does not have block-level scopes and only function scopes, the use of closures is closely related to functions.

Simulate private variables

Copy Code code as follows:

function Counter (start) {
var count = start;
return {
Increment:function () {
count++;
},
Get:function () {
return count;
}
}
}
var foo = Counter (4);
Foo.increment ();
Foo.get (); 5

Here Counter returns two closures: function increment and get. Both functions maintain access to the Counter scope, so they can always access the variable count that is defined in the Counter scope.

The working mechanism of private variables

Because Javascript can not assign values and references to scopes, in the example above, there is no way to directly access the internal private variable count in the external. The only way to do this is by defining a closed package access.

Copy Code code as follows:

var foo = new Counter (4);
Foo.hack = function () {
Count = 1337;
};

The above code does not change the value of the count variable within the Counter scope because hack is not defined within Counter. The above code will only create or overwrite global variable count.

Closure within a loop

One of the easiest mistakes to make is to use closures within a loop.

Copy Code code as follows:

for (var i = 0; i < i++) {
settimeout (function () {
Console.log (i);
}, 1000);
}

The above code does not output 0 to 9, but it outputs 10 consecutive 10.
The above anonymous will always hold a reference to the variable i. When you call the Console.log function to start outputting, this is the loop is over, and the variable i is already 10.
To avoid the above error, we need to create a copy of the variable I value at each loop.

Avoid referencing errors

In order to replicate the value of a variable in a loop, the best way is to add an anonymous immediate execution function to the outer layer.

Copy Code code as follows:

for (var i = 0; i < i++) {
(function (e) {
settimeout (function () {
Console.log (e);
}, 1000);
}) (i);
}

This external anonymous function receives the loop variable I as the first argument and copies its value to its own parameter E.
The external anonymous function passes the parameter e back to settimeout, so settimeout has a reference to the parameter E. And the value of this parameter e will not change because of an external loop change.

There is another way to achieve the same effect, which is to return an anonymous function in the anonymous function in settimeout:

Copy Code code as follows:

for (var i = 0; i < i++) {
SetTimeout ((function (e) {
return function () {
Console.log (e);
}
}) (i), 1000)
}

In addition, the Bind method can also be implemented.

Copy Code code as follows:

for (var i = 0; i < i++) {
SetTimeout (Console.log.bind (console, I), 1000);
}

At the end of the article we will conclude:

(1) Closure is a design principle, which simplifies the user's invocation by analyzing the context, so that the user can achieve his goal without knowing it;
(2) The online mainstream analysis of the closure of the article is actually and the closure principle of the reverse, if you need to know the closure details can be used well, this closure is the design failure;
(3) Learn as little as possible.

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.