"The iterator is bound to the context object."



Underscore.js文档说:

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

遍历一个元素列表,将每个元素依次返回给迭代器函数。如果传递了上下文对象,则将迭代器绑定到上下文对象。每次调用迭代器都带有三个实参:(element, index, list)。如果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...

上面加粗的文字是什么意思?有人能举个例子来解释吗?

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

相关内容

最新更新