JD *_*sco 3 javascript underscore.js
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...
Run Code Online (Sandbox Code Playgroud)
上面的粗体文字是什么意思?有人可以提供一个可以解释它的例子吗?
这意味着,在迭代器函数中,值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
Run Code Online (Sandbox Code Playgroud)
如果要将对象方法作为迭代器传递,并且该方法使用,则此方法很有用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
301 次 |
| 最近记录: |