我是 underscore.js 的新手。 _.each()
中的[context]
的作用是什么?应该怎么用?
最佳答案
上下文参数只是设置迭代器函数中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/
它使用被迭代的数组的每个成员的数字来获取 someOtherArray
的索引处的项目,它由 this
表示,因为我们将它作为上下文参数。
如果不设置上下文,那么 this
将引用 window
对象。
附加:
回答那有什么好处呢?为什么不直接引用 someOtherArray[num] 而不是 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
引用如何让我们在多个 _.each
调用中使用不同的 重复使用
值。如果我们在 iteratee
函数>上下文iteratee
中硬编码了 someOtherArray
,这将不起作用。
关于javascript - _.each(list, iterator, [context]) 中的上下文是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4946456/