JavaScript

This, Bind, Call, and Apply in JavaScript | Explained

Bind, call and apply are really useful and special methods that help us achieve borrowing of features and methods from one object to another using the reference “this”. This is a little advanced topic, that is why we are going to take things slow for you and explain every minute detail with examples.

JavaScript and many other programming languages use the keyword this to pass the reference of the parent object/class to its functions and methods inside them. While, the Bind, call and apply methods work on the passing of reference to borrow attributes from one object to another. The bind, call and apply feature was added in JavaScript in the ECMA2015 release.

The “this” reference

The keyword this has a very specific meaning in JavaScript, it refers to the object who is calling the function. If we are working with a constructor method then the keyword this would refer to the class and its properties, if we are working with some DOM elements then this keyword would refer to the global values of the DOM.

To demonstrate this, create the following object using the following lines:

var person = {
  name: "John Doe",
  age: 25,
  designation: "Auditor",
  printName: function () {
    console.log(this.name);
  },
};

As you can see, inside the object person we have a function printName which will print the name of the person, and inside the console.log() we can see that we have the line:

this.name;

This keyword is creating a reference to the object and tells the compiler to fetch the “name” from this particular object.

Call and apply methods

Call and apply can both be defined simultaneously because they have almost exactly the same working mechanics. Call and apply are used for function borrowing, function borrowing means to use the function of some other object and use the reference of some other object.

To understand this concept better, create two different objects using the following lines of code:

var person1 = {
  name: "John Doe",
  age: 25,
  designation: "Auditor",
  printName: function () {
    console.log(this.name);
  },
};

var person2 = {
  name: "Baba Yaga",
  age: 22,
  designation: "Unemployed",

};

As you can see in the code snippet, we have almost the same structure of both the objects and the same key-value pairs except for the fact that person1 has the function printName while person2 does not. But if you want to print out the “name” of the person2 object, you can do that by using the method “printName” from the person1 object, and for the “this” reference, you pass in the reference of the object person2.

Syntax of call and apply:

The syntax of both these methods is almost identical:

For call method the syntax is as:

obj1.function.call(refferenceOfObject2,arg1 arg2,arg3...);

For apply method the syntax is as:

obj1.function.apply(refferenceOfObject2,[arg1,arg2,arg3,...]);

Note: if the function that you are borrowing needs some additional arguments, then in the call method you pass in the arguments separated by a comma “, ” and in the case of the apply method, you pass additional arguments as an array list.

Using call and apply methods

Coming back to our original problem, we can use the “printName” function from the “person1” object to print out the name of the person2 object using the following line of code:

person1.printName.call(person2);

If you run the above command you will see the following output:

Similarly, you can use the apply() method for the same purpose using the of code:

person1.printName.apply(person2);

But what if the printName() function is taking in some arguments like:

printName: function (city, siblings) {
    console.log(`${this.name} from ${city} has ${siblings} siblings`);
 },

For this case, you will use the call function with the following line of code:

person1.printName.call(person2, "New York", 4);

The complete code snippet is as:

var person1 = {
  name: "John Doe",
  age: 25,
  designation: "Auditor",
  printName: function (city, siblings) {
    console.log(`${this.name} from ${city} has ${siblings} siblings`);
  },
};

var person2 = {
  name: "Baba Yaga",
  age: 22,
  designation: "Unemployed",
};

person1.printName.call(person2, "New York", 4);

If you execute the following code, you will get the output as:

As you can see, you were able to pass the arguments using the call method, you can do this by using the apply() method as well by using the following code snippet:

var person1 = {
  name: "John Doe",
  age: 25,
  designation: "Auditor",
  printName: function (city, siblings) {
    console.log(`${this.name} from ${city} has ${siblings} siblings`);
  },
};

var person2 = {
  name: "Baba Yaga",
  age: 22,
  designation: "Unemployed",
};

person1.printName.apply(person2, ["New York", 4]);

Note: for passing arguments to the borrowed function through the apply() method, we are using an array containing the arguments.

If you execute this code you will get the same identical output as:

But what if you don’t want to borrow a function from some object? This is where the bind method comes into play.

The bind() method

Unlike the call and apply methods, bind methods are used to create a copy of a function and then place that copied function as an attribute of the object so that the function can be used at a later time.

Syntax of the bind method

The syntax is as:

var newFunctionName = object1.function.bind(refereceToObject2);

Note: The bind method returns a function that is replicated.

To demonstrate this, let’s alter the code from the above example in this way:

var person1 = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  printFullName: function () {
    console.log(this.firstName + " " + this.lastName);
  },
};

var person2 = {
  firstName: "Baba",
  lastName: "Yaga",
  age: 25,
};

Now if you want to make a copy of the function printFullName from the object person1 and make it an attribute of the object person2 then you can do that by using the following line of code:

var printMyName = person1.printFullName.bind(person2);

With this line, you have “binded” an attribute function printMyName with the object person2, and you can invoke it using the command:

printMyName()

Note: You are not calling it with the person2 object by using the dot-operate because the reference to the person2 object is already “binded” to the function.

The complete code snippet is as:

var person1 = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  printFullName: function () {
    console.log(this.firstName + " " + this.lastName);
  },
};

var person2 = {
  firstName: "Baba",
  lastName: "Yaga",
  age: 25,
};

var printMyName = person1.printFullName.bind(person2);

printMyName();

When you execute this code snippet you get the following output:

There you go, you have duplicated a function from person1 object, passed the reference of person2 object, and stored it as a separate function.

Conclusion

Call, bind and apply methods are complicated methods that are used to play with the reference of the objects and help you to achieve feats like function borrowing and function replication with a different reference. To understand the details of these functions we need to know what the keyword this means in JavaScript and how referencing works in JS. You learned about the working of this, call, apply and bind methods along with their examples.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.