JavaScript advanced series-closures and references

Source: Internet
Author: User
Closure is a very important feature of JavaScript, which means that the current scope can always access variables in the external scope. Because a function is the only structure with its own scope in JavaScript, the creation of a closure depends on the function.
  • Simulate private variables

  • Why cannot I access private variables externally?

  • Closure in Loop

  • Avoid reference errors

Closure is a very important feature of JavaScript, which means that the current scope can always access variables in the external scope. Because a function is the only structure with its own scope in JavaScript, the creation of a closure depends on the function.

Simulate private variables

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

Here, the Counter function returns two closures: The increment function and the get function. Both functions maintain reference to Counter in the external scope, so you can always access the variable count defined in this scope.

Why cannot I access private variables externally?

Because JavaScript cannot reference or assign values to the scope, it is impossible to access the count variable externally. The only way is through the two closures.

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

The above Code does not change the value of the count variable defined in the Counter scope, because foo. hack is not defined in that scope. It will create or overwrite the global variable count.

Closure in Loop

A common error occurs when the closure is used in the loop. Suppose we need to call the loop serial number in each loop.

for(var i = 0; i < 10; i++) {    setTimeout(function() {        console.log(i);      }, 1000);}

The code above will not output numbers 0 to 9, but will output numbers 10 times.

When console. log is called, the anonymous function keeps referencing the external variable I. At this time, the for loop has ended and the I value has been changed to 10.

To get the expected result, you need to create a copy of variable I in each loop.


Avoid reference errors

In order to obtain the cyclic sequence number correctly, it is best to use the anonymous wrapper (note: we generally call self-executed anonymous functions ).

for(var i = 0; i < 10; i++) {    (function(e) {        setTimeout(function() {            console.log(e);          }, 1000);    })(i);}

External anonymous functions are executed immediately and I is used as its parameter. In this case, the e variable in the function has a copy of I.

When the anonymous function passed to setTimeout is executed, it has a reference to e, and this value will not be changed cyclically.

Another way to do the same is to return a function from the anonymous package. This is the same as the above Code.

for(var i = 0; i < 10; i++) {    setTimeout((function(e) {        return function() {            console.log(e);        }    })(i), 1000)}

The above is the JavaScript advanced series-closure and reference content. For more information, see the PHP Chinese website (www.php1.cn )!

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.