What is context in _.each(list, iterator, [context])? Ask Question

What is context in _.each(list, iterator, [context])? Ask Question

I am new to underscore.js. What is the purpose of [context] in _.each()? How should it be used?

ベストアンサー1

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

コンテキストを設定しない場合は、オブジェクトthisを参照しますwindow


特典:

What's the advantage of that? Why not just refer to someOtherArray[num] rather than this[num]?以下のコメントで高評価された質問に答えるために、匿名iterateeコールバックを関数に移動して簡単に再利用できるようにしましょう。

const someOtherArray  = ["name","patrick","d","w"];
const yetAnotherArray = ["what","goes","here","?"];

function alertStr(num){
    alert( this[num] );
}

_.each([1, 2, 3], alertStr, someOtherArray);
_.each([1, 2, 3], alertStr, yetAnotherArray);

参照によって、異なる値を持つ複数の呼び出しで関数をthis再利用できるようになることがわかります。内に がハードコードされていた場合、これは機能しません。iteratee_.eachcontextsomeOtherArrayiteratee

おすすめ記事