javascript - "The iterator is bound to the context object."

标签 javascript underscore.js

Underscore.js 文档说:

_.each(list, iterator, [context])

Iterates over a list of elements, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed. Each invocation of iterator is called with three arguments: (element, index, list). If list is a JavaScript object, iterator's arguments will be (value, key, list). Delegates to the native forEach function if it exists.

_.each([1, 2, 3], alert);
=> alerts each number in turn...
_.each({one : 1, two : 2, three : 3}, alert);
=> alerts each number value in turn...

上面加粗的文字是什么意思?有人可以提供一个例子来解释它吗?

最佳答案

这意味着,在您的迭代器函数中,this 的值将是您作为context 参数传递的值。

例如:

var arr = [1, 2, 3];
function iterator(el, i, list) {
    console.log(this)
}
_.each(arr, iterator, arr); // will log the whole array 3 times

如果您想将一个对象方法作为迭代器传递,并且该方法使用 this,这将很有用。示例:

var arr = [1, 2, 3];
var myObj = {
    foo : 5,
    addFoo : function(el, i, lst) {
       console.log(el + this.foo)
    }
};

// This will log NaN 3 times, because 'this' inside the function
// will evaluate to window, and there's no window.foo. So this.foo
// will be undefined, and undefined + 1 is NaN   
_.each(arr, myObj.addFoo);

// This, on the other hand, works as intended. It will get the value
// of foo from myObj, and will log 6, then 7, then 8
_.each(arr, myObj.addFoo, myObj); 

http://jsfiddle.net/KpV5k/

关于javascript - "The iterator is bound to the context object.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15647034/

相关文章:

javascript - 通过谷歌的 API 检索谷歌分析的行为流?

javascript - 返回没有特定值的对象

javascript - 打印从根节点到叶节点的所有路径 - javascript

javascript - 在返回填充的数组之前,如何在 NodeJS 中等待 foreach?

javascript - 如何在javascript Filter函数中过滤掉NaN

javascript - 在 Underscore.js 中递归/深度扩展/分配?

javascript - 主干 'this' 被设置为 'window'

javascript - Backbone.js 事件未触发

javascript - 从 Javascript 返回 Python Selenium 中的变量并用 selenium 更新它们

javascript - 使用jquery在div中添加一个又一个动画