call, apply and bind Methods in JavaScript
call, apply and bind are methods in JavaScript that allow changing function execution context and setting the this value for any function, regardless of how it was called. All three methods are related to context (this) binding, but have some differences in usage.
call Method
The call method allows calling a function with specified context and passing arguments as a list (comma-separated).
call Syntax
func.call(thisArg, arg1, arg2, ...);
call Usage Example
const person = {
name: "John"
};
function greet(greeting) {
console.log(greeting + ", " + this.name);
}
greet.call(person, "Hello"); // will output "Hello, John"
In this example this inside function greet points to object person because we used call to bind context.
apply Method
The apply method works similarly to call method, but arguments are passed as an array.
apply Syntax
func.apply(thisArg, [argsArray]);
apply Usage Example
const person = {
name: "John"
};
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
greet.apply(person, ["Hello", "!"]); // will output "Hello, John!"
In this example we pass arguments as an array to apply method.
bind Method
The bind method doesn't call function immediately. It returns a new function with pre-bound context (this) and specified arguments.
bind Syntax
const newFunc = func.bind(thisArg, arg1, arg2, ...);
bind Usage Example
const person = {
name: "John"
};
function greet(greeting) {
console.log(greeting + ", " + this.name);
}
const greetJohn = greet.bind(person); // create new function with bound this
greetJohn("Hello"); // will output "Hello, John"
The bind method is useful when you need to bind context in advance and pass a function that will be called later.
If you call bind multiple times, context will be bound only once
const greetAgain = greet.bind(person).bind({ name: "Jane" });
greetAgain("Hi", "?"); // will output "Hi, John?", because `bind` remembers only first context
Example Using All Three Methods
const person = {
name: "John"
};
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
// Using call
greet.call(person, "Hello", "!");
// Using apply
greet.apply(person, ["Hello", "!"]);
// Using bind
const greetJohn = greet.bind(person, "Hello", "!");
greetJohn(); // will output "Hello, John!"
bind Features:
The bind method always returns a new function, while call and apply immediately call the function with bound context.