Learn the concept
The this Keyword
call, apply, and bind are Function.prototype methods that explicitly set the `this` context. call and apply invoke the function immediately (call takes individual arguments, apply takes an array), while bind returns a new function with `this` permanently bound.
Function.prototype.call(thisArg, ...args)
thisFunction.prototype.apply(thisArg, [argsArray])
thisFunction.prototype.bind(thisArg, ...args)
this permanently boundthis cannot be overridden by call/apply/newKey Differences:
| Method | Invokes immediately? | Arguments format | Returns | |--------|---------------------|------------------|---------| | call | Yes | Individual | Result | | apply | Yes | Array | Result | | bind | No | Individual | New fn |
Arrow Functions:
thisthisthis from their enclosing lexical scopeCommon Patterns:
const user = {
name: 'Alice',
greet(greeting, punctuation) {
return `${greeting}, I'm ${this.name}${punctuation}`;
}
};
const bob = { name: 'Bob' };
// call — individual arguments
user.greet.call(bob, 'Hello', '!');
// "Hello, I'm Bob!"
// apply — array of arguments
user.greet.apply(bob, ['Hi', '?']);
// "Hi, I'm Bob?"
// bind — returns a new function
const bobGreet = user.greet.bind(bob, 'Hey');
bobGreet('.');
// "Hey, I'm Bob."
// bind is permanent — call/apply can't override it
bobGreet.call({ name: 'Charlie' }, '!');
// "Hey, I'm Bob!" — still BobBefore hooks, bind was essential in constructors to preserve 'this' context in event handlers passed as props
Libraries like Lodash use call/apply internally for method borrowing and to handle variadic functions across different contexts
Partial application with bind enables creating specialized functions from general-purpose ones without wrapper functions
Implement Function.prototype.myBind from scratch supporting partial application and new operator
Build a utility that borrows methods from one prototype to enhance array-like objects