What are the differences between Call, Apply and Bind in JavaScript?
call()
, apply()
, or bind()
allows us to use the functions of one object on a different object without having to make a copy of that method and maintain it in two separate places.
When to use .bind()?
We should use .bind()
when we want that function to be called later with a certain context, useful in events. bind() returns a function.
When to use .call() or .apply()?
Use .call()
or .apply()
when you want to invoke the function immediately, and modify the context.
Gist about Call, Apply and Bind:
Call invokes the function and allows you to pass in arguments one by one.
Apply invokes the function and allows you to pass in arguments as an array.
Bind returns a new function, allowing you to pass in this array and any number of arguments.
call() example:
Following is the code segment that describes the usage of the call() method.
const manObject = {firstName: 'Joe', lastName: 'Smith'}; const womanObject = {firstName: 'Jenny', lastName: 'Smith'}; function greetPeople(msg) { console.log(msg + this.firstName + ' ' + this.lastName); } greetPeople.call(manObject, 'Welcome Mr. '); // Welcome Mr. Joe Smith greetPeople.call(womanObject, 'Welcome Miss. '); // Welcome Miss Jenny Smith
apply() example:
Following is the code segment that describes the usage of the apply() method.
const manObject = {firstName: 'Joe', lastName: 'Smith'}; const womanObject = {firstName: 'Jenny', lastName: 'Smith'}; function greetPeople(msg) { console.log(msg + this.firstName + ' ' + this.lastName); } greetPeople.apply(manObject, ['Welcome Mr. ']); // Welcome Mr. Joe Smith greetPeople.apply(womanObject, ['Welcome Miss. ']); // Welcome Miss Jenny Smith
bind() example:
Following is the code segment that describes the usage of the bind() method.
const manObject = {firstName: 'Joe', lastName: 'Smith'}; const womanObject = {firstName: 'Jenny', lastName: 'Smith'}; function greetPeople() { console.log('Hello ' + this.firstName + ' ' + this.lastName); } const sayHelloJoe = greetPeople.bind(manObject); const sayHelloJenny = greetPeople.bind(womanObject); sayHelloJoe(); // Hello Joe Smith sayHelloJenny(); // Hello Jenny Smith