Topic 012: Call, Apply and Bind in JS
In JavaScript, call
, apply
, and bind
are methods that allow you to control the context (this
value) within which a function is executed. Here’s an explanation of each with examples:
call
MethodThe call
method calls a function with a given this
value and arguments provided individually.
Example:
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
const person = {
name: "Alice",
};
greet.call(person, "Hello", "!"); // Output: Hello, Alice!
apply
MethodThe apply
method calls a function with a given this
value and arguments provided as an array (or an array-like object).
Example:
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
const person = {
name: "Bob",
};
greet.apply(person, ["Hi", "!!"]); // Output: Hi, Bob!!
bind
MethodThe bind
method creates a new function that, when called, has its this
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Example:
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
const person = {
name: "Charlie",
};
const greetPerson = greet.bind(person, "Hey");
greetPerson("!!!"); // Output: Hey, Charlie!!!
this
)When these methods are not used, this
refers to the global object (in non-strict mode) or undefined
(in strict mode).
Example:
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
global.name = "Global"; // In browser environment, use `window.name = 'Global';`
greet("Hello", "!"); // Output: Hello, Global!
call
: Immediately invokes the function with a specified this
value and arguments.apply
: Immediately invokes the function with a specified this
value and arguments as an array.bind
: Returns a new function with a specified this
value and initial arguments, but doesn’t invoke it immediately.