【问题标题】:"The iterator is bound to the context object."“迭代器绑定到上下文对象。”
【发布时间】:2013-03-26 20:44:34
【问题描述】:

Underscore.js 文档说:

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

迭代一个元素列表,依次将每个元素生成一个迭代器函数。 如果传递了一个,则迭代器绑定到上下文对象。 每次调用迭代器时都使用三个参数:(元素、索引、列表)。如果 list 是 JavaScript 对象,迭代器的参数将是 (value, key, list)。如果存在,则委托给本机 forEach 函数。

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

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

【问题讨论】:

标签: javascript underscore.js


【解决方案1】:

这意味着,在您的迭代器函数中,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/

【讨论】:

  • 很好的例子。完全有道理,感谢您的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 2017-12-18
相关资源
最近更新 更多