Home Courses JavaScript Call vs Apply Explained - Change this Value Easily

JavaScript Call vs Apply Explained - Change this Value Easily

Why do we need call() and apply()?

  1. They are used to change the value of this
  2. They help in function reusability
  3. 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:

  1. If we call showDetails() directly, this will 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:

  1. call() sets this to the passed object
  2. 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"]);
Share this lesson: