Possible Duplicate:
underscore.js _.each(list, iterator, [context]) what is context?
So in the context of this forEach function in underscore.js:
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
What is the parameter context and how is it used?
Sets the
thisvalue (the calling context) of the iterator function that was passed.JavaScript’s
.calland.applymethods let you invoke a function with thethisvalue of the function you’re calling set to the first argument you provide.So if I do…
…the value of
thisinsidefuncwill be the{foo:"bar"}object.So if you provide that argument, underscore uses it as the first argument to
.callwhen invoking the function you passed as seen above.