Quiz 1124: JavaScript call, apply, bind
What are the differences between call()
, apply()
, and bind()
methods in JavaScript?
Quick Answer
call()
, apply()
, and bind()
are methods that allow you to change the context (this
) of a function. call()
and apply()
execute the function immediately, while bind()
returns a new function with the bound context. call()
and apply()
differ in how they handle arguments passed to the function.
Explain in Depth
In JavaScript, functions have a special object called this
that refers to the context in which they are called. These three methods, call()
, apply()
, and bind()
, allow you to manipulate the this
context within a function.
1. call()
call()
invokes a function immediately and allows you to pass arguments individually.
Syntax:
function.call(thisArg, arg1, arg2, ...)
thisArg
: The value ofthis
inside the function call.arg1, arg2, ...
: Individual arguments passed to the function.
Example:
function greet(message) {
console.log(`${message}, ${this.name}!`);
}
const person = { name: "TinyFrontend" };
greet.call(person, "Hello"); // Output: "Hello, TinyFrontend!"
2. apply()
apply()
also invokes a function immediately, but it accepts arguments as an array.
Syntax:
function.apply(thisArg, [arg1, arg2, ...])
thisArg
: The value ofthis
inside the function call.[arg1, arg2, ...]
: An array of arguments passed to the function.
Example:
function sum(x, y) {
return x + y;
}
const numbers = [2, 3];
const result = sum.apply(null, numbers); // Output: 5
3. bind()
bind()
returns a new function with thethis
value bound to a specific object. It doesn't execute the function immediately.
Syntax:
function.bind(thisArg, arg1, arg2, ...)
thisArg
: The value ofthis
inside the returned function.arg1, arg2, ...
: Arguments that will be prepended to the arguments passed to the returned function.
Example:
function greet(message) {
console.log(`${message}, ${this.name}!`);
}
const person = { name: "TinyFrontend" };
const boundGreet = greet.bind(person, "Welcome");
boundGreet(); // Output: "Welcome, TinyFrontend!"
Key Differences:
Method | Execution | Arguments | Returned Value |
---|---|---|---|
call() |
Immediate | Individual | undefined |
apply() |
Immediate | Array | undefined |
bind() |
Not Immediate | Individual | New function |
Use Cases:
call()
andapply()
are often used to borrow methods from other objects or to change the context of a function dynamically.bind()
is useful for creating partially applied functions or for ensuring that a function is called with a specificthis
value.