"The iterator is bound to the context object."

javascript, underscore.js

Solution

It means that, inside your iterator function, the value of `this` will be what you pass as the `context` argument.

For example:

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 is useful if you want to pass an object method as the iterator, and that method uses `this`. Example:

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/

Problem

The Underscore.js documentation says: _.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... ``` What does the bolded text above mean? Can someone provide an example that would explain it?

Original source

Related problems