3

Underscore.jsのドキュメントには次のように書かれています。

_.each(list、iterator、[context])

要素のリストを反復処理し、それぞれを反復子関数に生成します。イテレータが渡された場合、イテレータはコンテキストオブジェクトにバインドされます。イテレータの各呼び出しは、(要素、インデックス、リスト)の3つの引数で呼び出されます。listがJavaScriptオブジェクトの場合、イテレータの引数は(value、key、list)になります。ネイティブのforEach関数が存在する場合はそれを委任します。

_.each([1, 2, 3], alert);
=> alerts each number in turn...
_.each({one : 1, two : 2, three : 3}, alert);
=> alerts each number value in turn...

上記の太字のテキストはどういう意味ですか?誰かがそれを説明する例を提供できますか?

4

1 に答える 1

7

これは、イテレータ関数内で、の値が引数thisとして渡すものになることを意味します。context

例えば:

var arr = [1, 2, 3];
function iterator(el, i, list) {
    console.log(this)
}
_.each(arr, iterator, arr); // will log the whole array 3 times

これは、オブジェクトメソッドをイテレータとして渡し、そのメソッドがを使用する場合に役立ちますthis。例:

var arr = [1, 2, 3];
var myObj = {
    foo : 5,
    addFoo : function(el, i, lst) {
       console.log(el + this.foo)
    }
};

// This will log NaN 3 times, because 'this' inside the function
// will evaluate to window, and there's no window.foo. So this.foo
// will be undefined, and undefined + 1 is NaN   
_.each(arr, myObj.addFoo);

// This, on the other hand, works as intended. It will get the value
// of foo from myObj, and will log 6, then 7, then 8
_.each(arr, myObj.addFoo, myObj); 

http://jsfiddle.net/KpV5k/

于 2013-03-26T20:46:33.230 に答える