General Rule: Use .call() or .apply() when you want to execute a function in a different context or scope. *Keep in mind .call() and .apply() can only be called on functions.
var person1 = {name: 'Marvin', age: 20};
var person2 = {name: 'Zaphod', age: 30};
var sayHello = function(){
alert('Hello, ' + this.name);
};
var sayGoodbye = function(){
alert('Goodbye, ' + this.name);
};
Incorrect:
sayHello(); // Will produce errors because of scope issues
sayGoodbye(); // Will produce errors because of scope issues
Correct:
sayHello.call(person1); // The first parameter you pass .call will act as self
sayGoodbye.call(person2);
sayHello.apply(person1); // The first parameter you pass .apply will act as self
sayGoodbye.apply(person2);
The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price); //IMPORTANT LINE
this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);
var cheese = new Food('feta', 5);
var dispatch = function(person, method, args){
method.apply(person, args);
};
dispatch(person1, say, ['Hello']);
dispatch(person2, update, ['Bob', 20, 'Male']);
Resources: