I don't understand the purpose of a context variable for many of the underscore.js functions. What purpose does it serve. I know that it binds "this" in the iterator callback, but I don't understand the practical application of it.
var context = {'a': 'a'};
_.each([1, 2, 3], function(element, index, list)
{
console.log(this);
console.log(element);
console.log(index);
console.log(list);
}, context);
Underscore's _.each looks like this:
_.each(list, iterator, [context])
Contexts are very useful when your iterator is a member of some object you've created, and you want to execute that function in the scope of the object and not of the window. If your pre-written function that you're using as an iterator uses this to refer to an instance of an Object (as is generally the case), calling the function without context will result in this referring to the wrong thing.
It's useful if your iterator function is something like a method on an object:
var context = {'a': 'a', foo: function(x) { console.log( this.a + x); }};
_.each([1, 2, 3], context.foo, context);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With