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