What Is The Difference Between Call And Apply In JavaScript?

Introduction

JavaScript’s built in methods call and apply can be used to invoke a function using a given. context  this  property. JavaScript’s this property refers to the object that invoked the function.  this  is a global scope reference if it is accessed.window object. You may need to create an object with default value but later you might want to pass the properties to another object to substitute for the original context. Both call and apply are useful in this situation, as they both can invoke a function using an object passed. The following example illustrates this:


var Car = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 2016,
    getYear: function() {
        return this.year;
    }
};

Car.getYear(); // 2016

var newCar = {
    "brand": "Chevy",
    "model": "Camaro",
    "year": 2017
};

Car.getYear.call(newCar); //2017
Car.getYear.apply(newCar); //2017

It is clear that an object of Car was created with 2016 as the default model year. The value returned by get Model is correct for 2016. The year 2017 is returned when you invoke get Year from Car object using both the call/apply and newCar objects methods. This is just one example of how both apply and call can be used to invoke functions with an object or context.

Call vs. Apply

What is the difference between apply and call? They do the exact same thing. Both functions are nearly identical, except that additional arguments must be passed to the function being invoked. Let’s look at the Car object and add a function to accept model and brand as arguments. This will verify that it matches what is in the object.

var Car = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 2016,
    isEqual: function(brand, model) {
        if(this.brand == brand 
        && this.model == model) {
            return true;
        }
        return false;
    }
};

Car.isEqual("Ford", "Mustang"); // true

var newCar = {
    "brand": "Chevy",
    "model": "Camaro",
    "year": 2017
};

Car.isEqual.call(newCar, "Ford", "Mustang"); //false
Car.isEqual.apply(newCar, ["Ford", "Mustang"]); //false

Car.isEqual.call(newCar, "Chevy", "Camaro"); //true
Car.isEqual.apply(newCar, ["Chevy", "Camaro"]); //true

This example shows how arguments are passed and the difference between apply and call. These are the examples.callAccepts methodmultiple argumentsThese are passed to the invoked functions. TheapplyMethod accepts thearguments as an arrayThese are passed on to the invoked function. Once you understand the basic idea of when to call the call or apply methods, it’s quite simple.