The call(), apply(), and bind() methods in JavaScript are used to control the value of the this keyword when working with regular functions. These methods allow a function to use properties and methods from a specified object without requiring the function to be defined inside that object. The main difference is that call() and apply() execute a function immediately, while bind() returns a new function that can be executed later. In this article, we will learn how call(), apply(), and bind() work in JavaScript with simple examples.
Table of Contents
What Are call(), apply(), and bind() in JavaScript?
The call(), apply(), and bind() methods are available on JavaScript functions. They allow developers to specify the this value for a regular function.
These methods are useful when the same function needs to work with different objects.
Key differences:
- call() invokes a function immediately and accepts arguments individually.
- apply() invokes a function immediately and accepts arguments as an array or array-like object.
- bind() returns a new function with a specified this value and optional preset arguments.
What Is the call() Method?
The call() method invokes a function immediately with a specified this value. Additional arguments are passed individually, separated by commas.
Syntax:
functionName.call(thisValue, arg1, arg2, ...)
Example:
// JavaScript program to demonstrate the call() method
function greet(city, country) {
console.log("Hello, my name is " + this.name);
console.log("I live in " + city + ", " + country);
}
const person = {
name: "Rahul"
};
greet.call(person, "Mumbai", "India");
Output:
Hello, my name is Rahul
I live in Mumbai, India
In this example, call() sets this to the person object. The function then accesses this. name and receives "Mumbai" and "India" as individual arguments.
Example with two objects:
// JavaScript program to demonstrate call() with different objects
function introduce() {
console.log("My name is " + this.name);
}
const person1 = {
name: "Amit"
};
const person2 = {
name: "Priya"
};
introduce.call(person1);
introduce.call(person2);
Output:
My name is Amit
My name is Priya
Here, the same introduce() function is called with two different objects. The call() method determines which object is used as this for each invocation.
What Is the apply() Method?
The apply() method is similar to call(). It invokes a function immediately with a specified this value, but it accepts the function's arguments as an array or array-like object.
Syntax:
functionName.apply(thisValue, [arg1, arg2, ...])
Example:
// JavaScript program to demonstrate the apply() method
function calculateTotal(price, tax) {
console.log("Product:", this.product);
console.log("Total Price:", price + tax);
}
const item = {
product: "Laptop"
};
calculateTotal.apply(item, [50000, 5000]);
Output:
Product: Laptop
Total Price: 55000
In this example, apply() sets this to the item object and passes the values 50000 and 5000 as an array. The function adds the two values and displays the total price.
Example with an array of arguments:
// JavaScript program to demonstrate apply() with an array
function add(a, b, c) {
return a + b + c;
}
const numbers = [10, 20, 30];
const result = add.apply(null, numbers);
console.log("Sum:", result);
Output:
Sum: 60
Here, apply() passes the elements of the numbers array as the function arguments. Since the function does not use this, null is supplied as the this argument.
What Is the bind() Method?
The bind() method returns a new function with a specified this value. Unlike call() and apply(), it does not execute the function immediately.
The returned function can be called later. Arguments can also be supplied in advance.
Syntax:
const newFunction = functionName.bind(thisValue, arg1, arg2, ...)
Example:
// JavaScript program to demonstrate the bind() method
function greet() {
console.log("Hello, " + this.name);
}
const person = {
name: "Priya"
};
const boundGreet = greet.bind(person);
boundGreet();
Output:
Hello, Priya
In this example, bind() creates a new function called boundGreet. When it is called, this refers to the person object.
Example with preset arguments:
// JavaScript program to demonstrate bind() with preset arguments
function introduce(city, country) {
console.log(this.name + " lives in " + city + ", " + country);
}
const person = {
name: "Rohan"
};
const boundIntroduce = introduce.bind(person, "Pune");
boundIntroduce("India");
Output:
Rohan lives in Pune, India
Here, bind() sets this to the person object and presets "Pune" as the first argument. When boundIntroduce() is called, "India" is supplied as the second argument.
Difference Between call(), apply(), and bind()
The three methods have similar purposes, but they differ in how they pass arguments and execute functions.
| Basis | call() | apply() | bind() |
|---|---|---|---|
| Purpose | Calls a function | Calls a function | Creates a new function |
| Execution | Immediate | Immediate | Later, when the returned function is called |
| Arguments | Passed individually | Passed as an array or array-like object | Can be preset individually |
| Return value | Returns the function's result | Returns the function's result | Returns a new function |
| Changes this for a regular function | Yes | Yes | Yes, for the returned bound function |
| Common use | Calling a function with a specific object | Passing an array of arguments | Reusing a function with a fixed context |
Example comparing all three methods:
// JavaScript program to compare call(), apply(), and bind()
function showDetails(city, country) {
console.log(this.name + " lives in " + city + ", " + country);
}
const person = {
name: "Neha"
};
// Using call()
showDetails.call(person, "Mumbai", "India");
// Using apply()
showDetails.apply(person, ["Pune", "India"]);
// Using bind()
const boundShowDetails = showDetails.bind(person, "Delhi", "India");
boundShowDetails();
Output:
Neha lives in Mumbai, India
Neha lives in Pune, India
Neha lives in Delhi, India
In this example, all three methods set this to the person object. However, call() receives individual arguments, apply() receives an array, and bind() creates a function that can be executed later.
Using call(), apply(), and bind() with Objects
These methods allow objects to share a function without defining a separate copy of that function inside every object.
Example:
// JavaScript program to demonstrate sharing a method between objects
function displaySalary() {
console.log(this.name + "'s salary is " + this.salary);
}
const employee1 = {
name: "Amit",
salary: 25000
};
const employee2 = {
name: "Sneha",
salary: 30000
};
displaySalary.call(employee1);
displaySalary.call(employee2);
Output:
Amit's salary is 25000
Sneha's salary is 30000
Here, the displaySalary() function is shared between two objects. The call() method allows the function to access the properties of each object through this.
This approach reduces code duplication and makes functions reusable.
Advantages of call(), apply(), and bind()
The call(), apply(), and bind() methods provide several benefits in JavaScript.
- Control over this: They allow regular functions to use a specified object as their this value.
- Code reusability: A single function can work with multiple objects.
- Flexible argument handling: call() accepts individual arguments, while apply() accepts an array or array-like object.
- Deferred execution: bind() creates a function that can be called later.
- Reduced code duplication: Shared functions can be used by different objects without repeating their definitions.
Common Beginner Mistakes
- Confusing call() and apply(): Both methods execute a function immediately, but call() accepts individual arguments, while apply() accepts an array or array-like object.
- Expecting bind() to execute a function immediately: The bind() method returns a new function. You must call that function to execute the original function.
- Passing arguments in the wrong format: Arguments passed to call() should be individual values, while arguments passed to apply() should be provided as an array or array-like object.
- Assuming these methods can change this in an arrow function: Arrow functions inherit this from their surrounding lexical context. Using call(), apply(), or bind() cannot replace that lexical this value
- Forgetting that bind() returns a new function: Calling bind() does not modify the original function. Store the returned function if you want to reuse the bound context.
Conclusion
The call(), apply(), and bind() methods are important JavaScript features for controlling the this value of regular functions. The call() method executes a function with individual arguments, the apply() method executes it with arguments supplied as an array or array-like object, and the bind() method returns a new function for later execution. Understanding their differences helps developers reuse functions, work with objects, and write cleaner JavaScript code.
FAQs
1. What are call(), apply(), and bind() in JavaScript?
They are function methods used to specify the this value for regular functions. The first two execute a function immediately, while bind() returns a new function.
2. What is the main difference between call() and apply()?
The call() method accepts arguments individually, while apply() accepts arguments as an array or array-like object.
3. Does bind() execute a function immediately?
No. The bind() method returns a new function that can be executed later.
4. Can call(), apply(), and bind() change this in arrow functions?
No. Arrow functions inherit this from their surrounding lexical context, so these methods cannot change that value.
5. When should I use bind() in JavaScript?
Use bind() when you need a new function with a fixed this value, such as when passing a regular function as a callback.
0 Comments