2011-09-15 6 views
1

可能性の重複:
Javascript closure inside loops - simple practical exampleforループ内の無名関数から現在のループ反復を取得するには?

私は内部の匿名関数でループを持っている、との関数で、私は、現在のループの繰り返しにアクセスしたいです。しかし、ループの反復ではなく何らかの理由で、私は4になっています。唯一の他の場所4は、値myArray.lengthです。私が引数としてiを渡すと、[object Object]が出ます。私は間違って何をしていますか?私のコード:

var width = function(){ 
    for(var i = 0, len = myArray.length; i < len; ++i){ 
     alert(i) //this outputs the current iteration 
     myArray[i].load(function(){ 
     alert(i) //this outputs 4 (or [object Object]) 
     }); 
    }; 
}; 

ありがとう。

答えて

4

.loadに渡されたあなたの無名関数は、ループの終了後に実行されています。

はローカルスコープを作成する必要があり、かつi変数にコピー:

var width = function(){ 
    for(var i = 0, len = myArray.length; i < len; ++i){ 
     (function(i){ 
      myArray[i].load(function(){ 
       alert(i) //this outputs 4 (or [object Object]) 
      }); 
     })(i); 
    }; 
}; 
0

ECMAScript 5bind()[docs]を含み、それに結合しているthis値を持つ関数だけでなく、引数の値を取得するために使用されます。ここで

function loader(i){ 
    alert(i); 
} 

var width = function(){ 
    for(var i = 0, len = myArray.length; i < len; ++i){ 
     alert(i); 
     myArray[i].load(loader.bind(null, i) ); 
    } 
}; 

私が返される関数でthis値としてnullを拘束されていますが、何か他のものに設定することができます。次に、現在の値iを最初の引数としてバインドしました。


古いブラウザ(必要な場合)のサポートを取得するには、シムfrom MDNを含める:

if (!Function.prototype.bind) { 
    Function.prototype.bind = function (oThis) { 
     if (typeof this !== "function") // closest thing possible to the ECMAScript 5 internal IsCallable function 
     throw new TypeError("Function.prototype.bind - what is trying to be fBound is not callable"); 
     var aArgs = Array.prototype.slice.call(arguments, 1), 
      fToBind = this, 
      fNOP = function() {}, 
      fBound = function() { 
       return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments))); 
      }; 
     fNOP.prototype = this.prototype; 
     fBound.prototype = new fNOP(); 
     return fBound; 
    }; 
} 

これは、ほとんどの場合のために働くだろう、ほとんど互換性のシムです。

関連する問題