Examples of use of JS closures

Source: Internet
Author: User

On the internet about the closure of the introduction of too many, which led to the flooding, for the novice, the online a lot of talk about the closure is what, still use the following example:

Oh, my God, we've all seen how many times, what's the use of reading it? What's the occasion to use AH?

So I read all kinds of information, I summed up a bit:

I believe you can read my article before you should read a lot about the closure of the explanation, in fact, as long as you remember, the closure is the function inside a function, inside the function to access the parent function of the variable.

The following scenarios are used:

1. Xhr.addeventlistener ("Load", functionname, false);

What if functionname needs parameters?

A function can be defined again

function functionNameFnc(a){方法一    return function()   //方法二
{
// 标示 做functionName该做的事情 已经可以用参数了     }
}
xhr.addEventListener("load",functionNameFnc(a), false);

In this code, method two in method one, method two also uses the method one inside of the variable, closure!

2.

var a = [];for (var i = 0; i < 10; i++) {  a[i] = function () {    console.log(i);  };}

a[6](); // 10

变量i在整个函数内都有效没有得到释放。所以每一次循环,新的i值都会覆盖旧值,导致最后输出的是最后一轮的i的值。

The way to solve this problem is as follows:

for (Var i=0;i<10;i++) {
a[i]= (function (i) {

return function() {  console.log(i);})(i);

}
A[6] (); 6

Anonymous functions are used here to add that the biggest use of anonymous functions is to create closures (which is one of the features of the JavaScript language), the anonymous function is executed immediately, the execution is released, the closure of a flaw is that the variable has not been released, will lead to memory leaks.

These two examples should allow you to understand the use of closures ...

Examples of use of JS 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.