2013-03-26 52 views
3

的Underscore.js文檔說:「迭代器綁定到上下文對象。」

_.each(列表中,迭代器,[上下文])

在迭代元素的列表,得到每個依次迭代器功能。 迭代器綁定到上下文對象,如果通過。使用三個參數調用迭代器的每個調用:(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... 

什麼是黑體字上面的意思嗎?有人可以提供一個可以解釋它的例子嗎?

+0

相關:[underscore.js \ _每個(列表,迭代器,\ [背景\])是什麼背景?](http://stackoverflow.com/questions/ 4946456 /下劃線 - js-eachlist-iterator-context-what-is-context) – Bergi 2013-06-28 02:50:52

回答

7

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

+0

很好的例子。總體感覺,感謝解釋。 – 2013-03-26 21:45:46