我是下划线的新手。目的是什么[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
。