JavaScript Call vs Apply Explained - Change this Value Easily
Why do we need call() and apply()?
- They are used to change the value of
this - They help in function reusability
- Same function can be used with different objects
Example Objects
const user = {
name: "anil sidhu",
age: 29
}
const admin = {
name: "peter",
age: 45
}
const student = {
name: "sam",
age: 15
}
Common Function
function showDetails(city, country) {
console.log("my name is " + this.name + " and my age is " + this.age);
}
Problem:
- If we call
showDetails()directly,thiswill be undefined or global object.
call() Method
Syntax:
functionName.call(object, arg1, arg2)
Example:
showDetails.call(user, "noida", "india");
Output:
my name is anil sidhu and my age is 29
Explanation:
call()setsthisto the passed object- Arguments are passed comma-separated
Using call() with Different Objects
showDetails.call(admin);
showDetails.call(student);
Output:
my name is peter and my age is 45
my name is sam and my age is 15
apply() Method
Syntax:
functionName.apply(object, [arg1, arg2])
Example:
showDetails.apply(user, ["noida", "india"]);