JavaScript: bind() vs apply() and call()

The this refers to object can be different based on whether it is global, an object, and also on the usage of the three Function prototype methods — namely bind, call, and apply.

Call

The call() method calls the function with a given this value and allows passing in arguments one by one separating them with commas:

Javascript call method
let p1 = { firstName: 'John', lastName: 'Smith' }; let p2 = { firstName: 'Ann', lastName: 'Brown' }; function sayWelcome(greeting) { console.log(greeting + ' ' + this.firstName + ' ' + this.lastName); } sayWelcome.call(p1, 'Welcome'); // Welcome John Smith sayWelcome.call(p2, 'Welcome'); // Welcome Ann Brown

Apply

The apply() method calls the function with a given this value and allows passing in arguments as an array (or an array-like object).

JavaScript: bind() vs apply() and call()
let p1 = { firstName: 'John', lastName: 'Smith' }; let p2 = { firstName: 'Ann', lastName: 'Brown' }; function sayWelcome(greeting) { console.log(greeting + ' ' + this.firstName + ' ' + this.lastName); } sayWelcome.apply(p1, ['Welcome']); // Welcome John Smith sayWelcome.apply(p2, ['Welcome']); // Welcome Ann Brown
When the first argument is undefined or null, a similar result can be achieved using the array spread syntax.

The call() and apply() methods are interchangeable. Choosing between these two is up to the situation. If it is easier to send in an array, you can use apply() or call() for a comma separated list of arguments.

Bind

The bind() method returns a new function and allows passing in a this array and any number of arguments.

Javascript bind method
let p1 = { firstName: 'John', lastName: 'Smith' }; let p2 = { firstName: 'Ann', lastName: 'Brown' }; function sayWelcome() { console.log('Welcome ' + this.firstName + ' ' + this.lastName); } let sayWelcomeJohn = sayWelcome.bind(p1); let sayWelcomeAnn = sayWelcome.bind(p2); sayWelcomeJohn(); // Welcome John Smith sayWelcomeAnn(); // Welcome Ann Brown

Among these three methods above, bind() works a little bit differently. Unlike call() and apply() that execute the current function immediately, bind() returns a new function. You can use bind() for events like onClick where you don’t know when they will be fired but you know the desired context.