上下文参数只是设置的值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);
工作示例: http://jsfiddle.net/a6Rx4/ http://jsfiddle.net/a6Rx4/
它使用正在迭代的数组中每个成员的编号来获取该索引处的项目someOtherArray
,其表示为this
因为我们将它作为上下文参数传递。
如果不设置上下文,那么this
将参考window
object.
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
.