Introduction
JavaScript's call, apply, and bind methods are powerful tools that allow you to explicitly set the value of this in a function. These methods are often used to borrow methods from other objects or invoke functions in different contexts.
Note :"borrowing a method" refers to using a method from one object in the context of another object.
Syntax
function.call(thisArg, arg1, arg2, ..., argN);
function.apply(thisArg, [arg1, arg2, ..., argN]);
function.bind(thisArg, arg1, arg2, ..., argN);
Parameters:- thisArg: The value to which the this keyword should refer within the function when it is invoked. This can be any value (object, primitive, etc.).
- arg1, arg2, ..., argN: The arguments that will be passed to the function when it is invoked, arguments is optional.
What is Call?
The call method is a built-in JavaScript function that allows you to call a function with an explicitly specified this value. Additionally, arguments can be passed individually to the function being invoked.
This is especially useful when you want to borrow methods from one object and use them in the context of another object.
Passing Primitive Data Types (e.g., number, boolean, string)When you pass a primitive data type (like a number, string, or boolean) as the this value in the call method, it gets wrapped in a corresponding wrapper object (autoboxing), and the method executes with that wrapper object as this. However, primitive types cannot access the properties or methods of other objects directly.
// Define a simple function that uses "this"
function greet() {
console.log(this); // String {'John'}
const name = this.toString();
console.log(name); // 'John'
return "Hello, " + name;
}
// Use 'call' with a primitive string as "this"
console.log(greet.call("John")); // Output: Hello, JohnIn this example, when we use the string "John" as the this context, JavaScript wraps it in a string object, and the greet function uses that wrapper object. Therefore, the result is "Hello, John".
The call method can also be used to pass other objects like arrays as the this context.
// Define an object with a method that uses "this"
const person = {
introduce: function() {
console.log(this) //["John", 30]
return 'Hello, I am ' + this[0] + ' and I am ' + this[1] + ' years old.';
}
};
// Define an array with properties
const user = ['John', 30];
// Use 'call' to invoke 'introduce' with the array as the "this" value
console.log(person.introduce.call(user)); // Output: Hello, I am John and I am 30 years old.
In this case, we use the call method to invoke the introduce method on the person object, but we pass an array user as the this value. This works because arrays are objects, and their elements can be accessed using this[0] and this[1].
// Define an object with a method that uses "this"
const person = {
introduce: function() {
return 'Hello, I am ' + this.name + ' and I am ' + this.age + ' years old.';
}
};
// Define an array with properties
const user = {
name:"John",
age:35
}
// Use 'call' to invoke 'introduce' with the array as the "this" value
console.log(person.introduce.call(user)); // Output: Hello, I am John and I am 30 years old.
In this case, we use the call method to invoke the introduce method on the person object, but we pass the user object as the this value. This works because user is an object, and the introduce method uses this.name and this.age to access the properties of the user object. By calling introduce with user as this, the method correctly retrieves the values from the user object and outputs the string "Hello, I am John and I am 35 years old.
Note : Borrowing the 'introduce' method from 'person' and using it with 'user'
apply Method
The apply method is similar to call, but it takes arguments as an array or an array-like object.
const person = {
fullName: function(city, country) {
return this.firstName + ' ' + this.lastName + ', ' + city + ', ' + country;
}
};
const user = {
firstName: 'Jane',
lastName: 'Doe'
};
console.log(person.fullName.apply(user, ['New York', 'USA']));
// Output: Jane Doe, New York, USAIn this case, we use the apply method to invoke the fullName method on the person object, but we pass the user object as the this value. The key difference with apply is that it takes arguments as an array (or array-like object). In this example, we pass ['New York', 'USA'] as the array of arguments. The fullName method then correctly accesses the firstName and lastName properties of the user object, and the city and country are passed as arguments. The result is the string "Jane Doe, New York, USA."
bind Method
The bind method is similar to call, but instead of invoking the function immediately, it returns a new function with a bound this value, which can be called later.
const person = {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
const user = {
firstName: 'Emily',
lastName: 'Smith'
};
const boundFunction = person.fullName.bind(user);
console.log(boundFunction()); // Output: Emily SmithWhen to Use Them?
Use call and apply when you need to execute a function immediately with a specifiedthis. Use bind when you want to create a function with a pre-set this value for later use.
Difference
Detailed Comparison of call, apply, and bind :
| Method | Arguments | Execution | Use Cases |
|---|---|---|---|
call | Comma-separated values, passed individually. | Executes the function immediately with the specified this context. |
|
apply | Arguments passed as an array or array-like object. | Executes the function immediately with the specified this context. |
|
bind | Comma-separated values, passed individually. | Returns a new function with the specified this context, executed later when invoked. |
|
Additional Explanation
These three methods allow us to control the this context of a function dynamically and are fundamental tools for working with JavaScript functions.
call
The call method invokes the function immediately and requires arguments to be passed individually as comma-separated values. It's often used when you know the exact number of arguments and want to call the function directly.
function introduce(greeting, punctuation) {
return greeting + ', ' + this.name + punctuation;
}
const user = { name: 'Alice' };
console.log(introduce.call(user, 'Hello', '!')); // Output: "Hello, Alice!"apply
The apply method is similar to call but expects arguments in the form of an array. It's especially useful when working with functions that require array-like inputs or when the arguments are dynamically determined.
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum.apply(null, numbers)); // Output: 6bind
The bind method does not execute the function immediately. Instead, it returns a new function with the specified this context and pre-filled arguments (if provided). This is useful for creating functions to be executed later, often in event listeners or callbacks.
function greet() {
return 'Hello, ' + this.name;
}
const user = { name: 'Bob' };
const boundGreet = greet.bind(user);
console.log(boundGreet()); // Output: "Hello, Bob"Key Takeaways
Understanding call, apply, and bind is essential for mastering JavaScript, especially when working with functions in dynamic contexts. Practice these methods to strengthen your grasp of JavaScript's this mechanism.