A method for accessing external variables by JavaScript closure functions _javascript Tips

Source: Internet
Author: User
Tags anonymous closure

Closures are functions that have access to variables in the scope of another function, but the scope configuration mechanism has a need to note that closures can only take the last value that contains any variable in the function.

such as the following cases:

function Create () {
var arr = new Array ();
For (Var i=0. i<10; i++) {
Arr[i] = function () {return
i;
};  
}
return
arr;
}
var C_arr = Create ();
For
(var i=0 i<c_arr.length;i++) {
document.write ("c_arr[" +i+ "] =" +c_arr[i] () + "<br/>"); 
}

Execution results:

On the surface, it seems that each function returns a different I value, such as the value of c_arr[0] should be the value of 0,c_arr[1] should be 1, and so on. You can result in a return of 10 for each function. Why, then?

Because the active object of the Create () function is kept in the scope chain of each function, they refer to the same variable i. When the For loop ends, the value of I becomes 10, at which point each function references the same variable object that holds the variable i.

We can force the closure behavior to conform to expectations by creating another domain name function, so that each position corresponds to the corresponding value.

function Create () {
var arr = new Array ();
For (Var i=0. i<10; i++) {
Arr[i] = function (num) {return
function () {
re            Turn num; 
};
} (i);  
}
return
arr;
}
var C_arr = Create ();
For
(var i=0 i<c_arr.length;i++) {
document.write ("c_arr[" +i+ "] =" +c_arr[i] () + "<br/>"); 
}

Execution results:

An anonymous function is defined and the machine that executes the anonymous function is assigned to the array, where the anonymous function has a parameter num, which is the value returned by the final function. We pass in the variable i when we call each function. Because function arguments are passed by value, the current value of the variable i is assigned to parameter Num. Within this anonymous function, a closure that accesses NUM is created and returned, so that each function in the ARR array has a copy of its own num variable, so it is possible to return different values.

Classic examples

Let's take a look at a classic example, assuming that the page has a set of button tags, and we use the script to bind the button tag to the event, and then click to eject this is the first few tags.

<meta charset= "Utf-8"/>
<button> First </button>
<button> second </button>
<button> Third </button>
<button> fourth </button>
<script type= "text/ JavaScript ">
var obj = document.getelementsbytagname (' button ');
for (Var i=0;i<obj.length;i++) {
Obj[i].onclick = function () {
alert (i);
};  
}
</script>

Click on the results of each button

On the surface, it seems that clicking each label should pop up a different number

The first one should pop 0;

The second one should pop 1;

Analogy

But the result is that all the buttons pop up 4, which is obviously not the result we want.

Let's change the procedure.

<meta charset= "Utf-8"/>
<button> First </button>
<button> second </button>
<button> Third </button>
<button> fourth </button>
<script type= "text/ JavaScript ">
var obj = document.getelementsbytagname (' button ');
for (Var i=0;i<obj.length;i++) {
Obj[i].onclick = function (num) {return
function () {
alert (num);
} 
(i);  
}
</script>

Click on a second

Click on the fourth one

We only need to create an anonymous function within a function, similar to the case above. You can implement an anonymous function to capture an external variable i, which results in a different I value for each button bullet.

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.