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

2023-12-20

我是 underscore.js 的新手。目的是什么[context] in _.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);

工作示例: 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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐