Skip to content

Instantly share code, notes, and snippets.

@rootulp
Last active January 15, 2019 01:13
Show Gist options
  • Save rootulp/fb1cd6f09e02078717a9 to your computer and use it in GitHub Desktop.
Save rootulp/fb1cd6f09e02078717a9 to your computer and use it in GitHub Desktop.
.call() VS .apply() - Lightning Talk

Javascript .call() VS .apply()

When to use .call() or .apply()?

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);

Difference between .call() and .apply()

The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.

Example of .call()
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);
Example of .apply()
var dispatch = function(person, method, args){
    method.apply(person, args);
};

dispatch(person1, say, ['Hello']);
dispatch(person2, update, ['Bob', 20, 'Male']);

Resources:

Blog Post Explanation

Stack Overflow Explanation

Mozilla Docs .call()

Mozilla Docs .apply()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment