Call, Apply, Bind
Overview
Because the this keyword is so notoriously unstable, JavaScript provides three built-in methods (call, apply, and bind) that allow you to manually override and lock down what the this keyword points to for a specific function.
- call & apply: Execute the function immediately with the overridden context. - bind: Returns a brand new function with the overridden context locked in, which you can execute later.
Syntax
const person1 = { name: "Kartik" };
const person2 = { name: "Aman" };
function greet(greeting, punctuation) {
console.log(`${greeting} ${this.name}${punctuation}`);
}
// .call(thisArg, arg1, arg2...)
greet.call(person1, "Hello", "!"); // "Hello Kartik!"
// .apply(thisArg, [argsArray]) - Takes an ARRAY!
greet.apply(person2, ["Hi", "."]); // "Hi Aman."// .bind(thisArg) returns a new function
const greetKartik = greet.bind(person1);
// Can be executed hours later, 'this' is permanently locked!
greetKartik("Welcome", "!!");Common Pitfalls
- Confusing
callandapplyduring an interview. The classic mnemonic device is: Apply takes an Array of arguments. Call takes Comma-separated arguments.
Interview Questions
call() and bind()?call() immediately invokes the function with the specified this context. bind() does not execute the function; instead, it returns a brand new function with the this context permanently locked in, which can be executed at a later time.
Real-World Example
Borrowing methods from other objects. For example, borrowing Array methods to use on Array-like objects (like arguments or NodeLists) that don't natively have them.
const argsArray = Array.prototype.slice.call(arguments);Check Your Knowledge
Test your understanding of Call, Apply, Bind with these quick questions.