Let’s break down call, apply, and bind in a simple way with easy examples. All three are used to set the value of this in a function, but they work slightly differently.
- call()
- What it does: Calls a function immediately with a specified this value and arguments passed one by one.
- Syntax:
- function.call(thisArg, arg1, arg2, ...)
- Example:
function greet(greeting, punctuation) {
console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}
const person = { name: "Kishan" };
greet.call(person, "Hello", "!");
// Output: "Hello, my name is Kishan!"
Key Point:
- call() immediately executes the function.
- Pass arguments separately.
- apply()
- What it does: Calls a function immediately with a specified this value and arguments passed as an array.
- Syntax:
- function.apply(thisArg, [arg1, arg2, ...])
- Example:
greet.apply(person, ["Hi", "."]);
// Output: "Hi, my name is Kishan."
Key Point:
Similar to call(), but you pass arguments as an array.
- bind()
- What it does: Returns a new function with a specified this value. It does not execute the function immediately.
- Syntax:
- const newFunction = function.bind(thisArg, arg1, arg2, ...)
- Example:
const greetKishan = greet.bind(person, "Hey", "!!");
greetKishan();
// Output: "Hey, my name is Kishan!!"
Key Point:
bind() returns a new function that you can call later.
Useful when you want to save a function with a specific this for later use (e.g., event handlers).
Top comments (0)