Javascript tips — Apply vs. Call vs. Bind

Image for postPhoto by Nicole Wilcox on Unsplash

Hi! Today I?ll talk about the differences between apply vs. call vs. bind. These JavaScript methods allow you to change the value of ?this? for a given function.

Function.prototype.call()

The method Call invokes the function and allows you to pass in arguments one by one using commas.

let customer1 = { name: ‘Leo’, email: ‘[email protected]’ };let customer2 = { name: ‘Nat’, email: ‘[email protected]’ };function greeting(text) { console.log(`${text} ${this.name}`);}greeting.call(customer1, ‘Hello’); // Hello Leogreeting.call(customer2, ‘Hello’); // Hello Nat

Function.prototype.apply()

The method Apply invokes the function and allows you to pass in arguments as an array.

let customer1 = { name: ‘Leo’, email: ‘[email protected]’ };let customer2 = { name: ‘Nat’, email: ‘[email protected]’ };function greeting(text, text2) { console.log(`${text} ${this.name}, ${text2}`);}greeting.apply(customer1, [‘Hello’, ‘How are you?’]); // output Hello Leo, How are you?greeting.apply(customer2, [‘Hello’, ‘How are you?’]); // output Hello Natm How are you?

Function.prototype.bind()

The Bind method returns a new function, allowing you to pass in a this array and any number of arguments. Use it when you want that function to later be called with a certain context like events.

let customer1 = { name: ‘Leo’, email: ‘[email protected]’ };let customer2 = { name: ‘Nat’, email: ‘[email protected]’ };function greeting(text) { console.log(`${text} ${this.name}`);}let helloLeo = greeting.bind(customer1);let helloNat = greeting.bind(customer2);helloLeo(‘Hello’); // Hello LeohelloNat(‘Hello’); // Hello Nat

The Bind implementation would be like this:

Function.prototype.bind = function(context) { var fn = this; return function() { fn.apply(context, arguments); };};

Call and Apply are interchangeable. You can decide whether it?s easier to send in an array or a comma separated list of arguments. Bind is different. It always returns a new function.

We can use Bind to curry functions like in the example. We can take a simple hello function and turn it into a helloJon or helloKelly. You can use it for events where we don?t know when they?ll be fired but know what context is.

That?s all folks,

Thanks for reading.

Function.prototype.call()

The call() method calls a function with a given this value and arguments provided individually.

developer.mozilla.org

Function.prototype.apply()

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like?

developer.mozilla.org

Function.prototype.bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a?

developer.mozilla.org

15

No Responses

Write a response