I've been driving myself a bit mad trying to figure out how to make this code work. My goal is to produce the output larry eats pie, larry eats candy, larry eats cake by binding the function eats within the alice object to the larry object. My hope with the code below was that binding the alice.eats function to the larry object would use larry as this.name, and subsequently applying that function using an array of larryFoods, I would hope that it would produce larry eats + [food] for each argument.
//-----------------Does not work--------------//
var alice = {
name: "alice",
speak: function(){
console.log("Hi, I'm " + this.name);
},
eats : function(){
var theArgs = Array.prototype.slice.call(arguments);
theArgs.forEach(function(arg){
console.log(this.name + " eats " + arg);
});
}
};
var larry = {
name: "larry"
};
var larrySpeak = alice.speak.bind(larry);
larrySpeak();
var larryFoods = [" pie", " candy", " and cake"];
var larryEats = alice.eats.bind(larry);
larryEats.apply(larryFoods);
I am assuming that the forEach function will operate in the global context, which is why I was hoping bind would solve the problem. Any insight would be most welcome.
forEachcallback has a newthis, so you lost the context there.