call, apply & bind

In JavaScript, call, apply, and bind are methods used to explicitly set the this context of a function. This is crucial when you want to control what this refers to inside a function, especially when borrowing methods or working with callbacks.

Illustration of call_apply_bind
Illustration of call_apply_bind

💡 What is this?

this refers to the object that is executing the current function. By default, it can vary based on how a function is called.

call()

Calls a function with a specified this context and arguments passed individually.

📌 Deep Dive: Using call

JAVASCRIPT
function greet(greeting, punctuation) {
  console.log(greeting + ', ' + this.name + punctuation);
}

const person = { name: 'Alice' };
greet.call(person, 'Hello', '!'); // Hello, Alice!
Output
Hello, Alice!

apply()

Similar to call, but arguments are passed as an array.

📌 Deep Dive: Using apply

JAVASCRIPT
greet.apply(person, ['Hi', '...']); // Hi, Alice...
Output
Hi, Alice...

bind()

Returns a new function permanently bound to a specified this context and optionally preset arguments. It does not call the function immediately.

📌 Deep Dive: Using bind

JAVASCRIPT
const greetAlice = greet.bind(person, 'Hey');
greetAlice('!!'); // Hey, Alice!!
Output
Hey, Alice!!
Comparison: call, apply & bind
MethodArgumentsReturnsWhen to use
callList of argumentsFunction resultInvoke immediately with this and arguments
applyArguments as arrayFunction resultInvoke immediately with this and array arguments
bindList of arguments (optional)New bound functionCreate a function with fixed this and optional preset arguments

💡 Key Point

call and apply invoke the function immediately, while bind returns a new function for later use.

⚠️ Common Mistake

Don't forget that bind does not call the function — you must call the returned function explicitly.