javascript - _.each(list, iterator, [context]) 中的上下文是什么?

标签 javascript functional-programming underscore.js this

我是 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/

相关文章:

javascript - iframe问题和覆盖

javascript - 使用 Javascript、jQuery 和 underscore.js 从多维数组中删除重复项

javascript - 如何使用 van Laarhoven Lens 删除对象的聚焦属性?

data-structures - 权重偏左的堆 : advantages of top-down version of merge?

javascript - 在 Node.js 中的函数中访问 __dirname 是否被视为不纯代码?

javascript - 下划线 : remove all key/value pairs from an array of object

javascript - 变种未定义=无效0; vs jquery 的关闭 vs ...?

javascript - 为什么 promise 在 setTimeout 之前解决

javascript - 如何在元素html内添加元素数据属性值

javascript - 需要在 body onload 事件之前在 Web 表单上运行 Javascript