Reputation: 956
In a tutorial I'm watching on underscore this code is used to demonstrate _.each
:
var people = {
names: ['Craig', 'John', 'Dan', 'Elijah'],
getMessage: function(name) {
return 'Hello there, ' + name + '!';
}
};
_.each(people.names, function(element, index, list) {
console.log(this.getMessage(element))
}, people);
It's explained that people
gets passed as the context for the _.each
call to bind this
to the people
object but I don't understand why this is necessary. In the body of the iterator function couldn't I just explicitly write out people.getMessage
?
like:
_.each(people.names, function(element, index, list) {
console.log(people.getMessage(element));
});
Why use this
and have to pass in a context at all?
Upvotes: 1
Views: 59
Reputation: 403
Like mentioned in the comments, it is not necessary but it can be useful in certain cases. It also keeps the iterator function unaware of the scope above. It only knows it's dealing with objects that have a getMessage()
method and not linked to a specific variable in the closure.
One example i can think of is to be able to reuse that for different objects that have the same sort of structure but are not named people
in the scope.
var people = {
names: ['Craig', 'John', 'Dan', 'Elijah'],
getMessage: function(name) {
return 'Hello there, ' + name + '!';
}
};
var dogs = {
names: ['Jimmy', 'Rufus', 'Woofie', 'Silly'],
getMessage: function(name) {
return 'Woof there, ' + name + '!';
}
};
function logTheMessage(element) {
console.log(this.getMessage(element));
}
_.each(people.names, logTheMessage, people);
_.each(people.names, logTheMessage, dogs);
Upvotes: 1