Mastering the Art of Borrowing: call, apply, and bind in JavaScript
Ever wondered how functions in JavaScript can do magic tricks like changing their context or having pre-baked arguments? Well, the secret lies in three special methods: call, apply, and bind.
Think of these methods as borrowing tools for functions. They let you use a function's power in different ways, just like borrowing a wrench to fix something.
Here's a breakdown of each method
CALL()
Imagine you need someone to pass specific instructions (arguments) to your function one by one. That's where call
comes in. It takes care of delivering those instructions directly to the function.
function greet(name){
console.log(`Hello, ${name}, I'am ${this.title}`);
}
const person = {
title: 'Mr.',
}
// Using call to invoke the function with a specific 'this' value
greet.call(person,'mathi');
function.call(thisArg, arg1, arg2, ...);
Call method arguments
Apply()
Similar to call
, but instead of giving instructions one at a time, you can gather them all in a list (array) and hand it over to the function. apply
will unpack the list and deliver the instructions individually.
/*
The apply method is similar to call, but it takes an array of
arguments instead.
*/
// Example function
function personDisplay(a, b) {
console.log(`Display: ${a + b}. I'm ${this.title}`);
}
// Object to set as 'this'
const person = { title: 'mathi' };
// Using apply to invoke the function with a specific 'this' value and an array of arguments
sum.personDisplay(person, [5, 10]);
bind()
The bind
method is used to generate a new function that has a predetermined this
value and initial arguments. Importantly, it does not immediately execute the function. Instead, it retains the newly created function, allowing it to be invoked later by calling the variable to which it's assigned whenever needed.
// Create a function with pre-baked arguments
const doubleValue = multiply.bind(null, 2);
// Use the new function with different arguments
console.log(doubleValue(5)); // Output: 10
// Create another function with different arguments
const tripleValue = multiply.bind(null, 3);
// Use both functions for different computations
console.log(doubleValue(10)); // Output: 20
console.log(tripleValue(7)); // Output: 21
Benefits of using these methods
Reusable code: You can borrow the same function for multiple purposes, saving you time and effort.
Context control: You can change the context in which the function is executed, making it more flexible.
Partial application: You can pre-fill some arguments in a function, making it easier and more efficient to use.
Subscribe to my newsletter
Read articles from Mathi Yuvarajan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Mathi Yuvarajan
Mathi Yuvarajan
Empowering communities via open source and education