我是下划线的新手。目的是什么[context]_.each()

答案

上下文参数只是设置了this在迭代函数中。

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/

它使用迭代阵列中每个成员的数字,以获取该项目的索引someOtherArray,由this由于我们将其作为上下文参数传递。

如果您不设置上下文,则this将参考window目的。


Extras:

回答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跨多个函数_.each调用不同的context价值观。someOtherArray硬编码在里面iteratee

来自: stackoverflow.com