开发者

How to access this variable in an inline function?

Here is my dilemma.

I've got this section of code:

var list_of_numbers = new Array();

function AddToArray(func)
{
    // Add to the *beginning* of the array
    // essentially reversing the order

    list_of_numbers.unshift(func);
}

function DisplayNumber(num)
{
    document.write(num);
}

for(var i=0;i<5;++i)
{
   AddToArray(function() { DisplayNumber(i); });
}

for(var i=0;i<5;++i)
{
   list_of_numbers[i]();
}​

What is supposed to happen is that 5 inlin开发者_高级运维e functions will be added to the array - each taking a copy of i. However this does not happen.

Expected output:

43210

Actual output:

01234


You have two separate issues, both related to scope.

var list_of_numbers = new Array(); 
function AddToArray(func) 
{ 
    // Add to the *beginning* of the array
    // essentially reversing the order 
    list_of_numbers.unshift(func); 
} 

function DisplayNumber(num) 
{ 
    document.write(num); 
} 
for(var i=0;i<5;++i) 
{ 
    (function(i) 
     { 
         AddToArray(function(){ DisplayNumber(i); });
     })(i); 
} 

for(var j=0;j<5;++j) 
{ 
    list_of_numbers[j](); 
}​
  1. The anonymous function you're passing to AddToArray is bound to the variable i, not the current value. To address this, we create a new function, and pass in the current i.

  2. JavaScript has function scope, so when you re-declare i in the second loop, you're still modifying the same variable. Thus, we rename it to j.

If only the first were an issue, you would get 55555, since all functions would use the same i, at that point 5. However, since you reuse i for the second index, i is set to the current loop index.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜