closures and variables

来源:互联网 发布:没卡怎么在淘宝买东西 编辑:程序博客网 时间:2024/06/06 12:43

There is one notable side effect of this scope-chain configuration. The closure always gets the last value of any variable from the containing function.Remember that the closure stores a reference to the entire variable object, not just to a particular variable.This issue is illustrated clearly in the following example:

function createFunctions() {let reslt=[];for(let i=0;i<10;i++){reslt[i]=function () {return i;}}return reslt;}

This function returns an array of functions. Since each function has the createFunctions() activation object in its scope chain, they are all referring to the same variable, i .

You can, however, force the closures to act appropriately by creating another anonymous function, as follows:


function createFunctions() {let reslt=[];for(let i=0;i<10;i++){reslt[i]=function(num){return function () {return num;}}(i);}return reslt;}

With this version of  createFunctions(), each function returns a different number. Instead of assigning a closure directly into the array, an anonymous function is defined an called immediately. The anonymous function has one argument,num, which is the number that the result function should return. The variable i is passed in as an argument to the anonymous function. Since function arguments are passed by value, the current value of i is copied into the argument num. Inside the anonymous function, a closure that accesses num is created returned. Now each function in the result array has its own copy of num and thus can return separate numbers.