Bind, call and apply
There are 3 similar but differently used functions. Below we'll look at differences between apply vs. call vs. bind.
- Bind is useful when you want to create a copy & returns a new function to be executed when required
- Apply/Call are similar but differ in how parameters are passed. Unlike bind, they are used to execute the function now.
function greeting(text) {
console.log(`${text} ${this.name}`);
}
Let's see how to invoke above bound by below two objects in different ways with
" bind, call & apply " variants:
-
let customer1 = { name: 'Leo', email: 'leo@gmail.com' }
-
let customer2 = { name: 'Nat', email: 'nat@hotmail.com' };
Function.prototype.call()
The method Call invokes the function and allows you to pass in arguments one by one using commas. The buttons here actually use the functions as mentioned in the code.
Function.prototype.apply()
The method Apply invokes the function and allows you to pass in arguments as an array. The buttons below actually use the functions as mentioned in the code
Function.prototype.bind()
The Bind method returns a new function with predefined provided context & arguments. The buttons in example here use the functions as mentioned in the code.
Function.prototype.bind = function(context, ...boundArgs) {
var fn = this;
return function(...functionArgs) {
fn.apply(context, [...boundArgs, ...functionArgs]);
};
};
References:
- Good medium article by Leonardo Bruno Limahttps://medium.com/@leonardobrunolima/javascript-tips-apply-vs-call-vs-bind-d738a9e8b4e1
- Nice explanation on StackOverflowhttps://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind
- ELI5 on same by Omer Goldberghttps://medium.com/@omergoldberg/javascript-call-apply-and-bind-e5c27301f7bb