Divaksh
/Brief Understanding of this, bind, apply, & call in JavaScript

Brief Understanding of this, bind, apply, & call in JavaScript

Compiled on May 02 2021 in JavaScript

Today in this article we will learn about the keyword 'this' and some different functions of JavaScript that enhance the utility of the keyword 'this'. This remains a very confusing and debating topic for JavaScript developers. People also say that this is extremely hard to understand "this", but today in this discussion, we will make this easier for you.

What is this in JavaScript?

Let me explain it layman language. Just as, in English grammar, the word 'this' is used to pointing out at some object, in JavaScript 'this' is used for the same purpose.

In JavaScript, this keyword refers to the object, but the question is, which object 🤔? The answer is "the object which refers to the execution of the current part of the code". Now just keep it in your mind that 'this' keyword binds with an object. Binding of 'this' keyword also happens in two✌️ ways.

  1. Implicit Binding: Implicit binding happens when you don't put extra efforts for binding 'this' keyword. Usually, it happens when you invoke a property of an object using dot notation.
  2. Explicit Binding: Explicit binding is done with the help of inbuilt functions of JavaScript like bind(), call(), apply().

Let's try to understand implicit binding and explicit binding in depth

Implicit Binding

We will learn the concept of implicit binding of 'this' keyword with different references:

Global Execution Context:

Each section of the code which is not the part of any function is comes under the global execution context. For example, if you write in browser's console.

console.log(this); 
//Output:
Window {parent: Window, opener: null, top: Window, length: 1, frames: Window,}

You see it because the window is the global object of a browser. Let's see another example.

function person(){
   console.log(this.name);
}

var name = "Anubhav👴";

var obj1 = {
  name: "Divaksh🙍‍♂️",
  age: 30,
  person: person
};
var obj2 = {
  name: "Ayushi🙎‍♀️",
  age: 27,
  person: person
};

person(); //Output: Anubhav👴
obj1.person(); //Output: Divaksh🙍‍♂️
obj2.person(); //Output: Ayushi🙎‍♀️

In the above code, you see a function which prints the name attribute of the object which is referenced to the current execution context. Current execution context means the bit of code which is in execution at the present time.

Firstly, the function person() prints "Anubhav👴", which is the value of variable 'name', because this time the current execution context is the global execution context.

Second time function person() is called with the execution context of obj1 and because of this it prints the value of name attribute of obj1, and so in the case of obj2.

Method of an object:

By method, I simply mean the functions of an object. Now why are we considering this here? Because these methods use this keyword for referring the properties/attributes of the objects they are related to. For example, 

const person = {
   name: "Ayushi 😎",
   age: 27,
   printPerson(){
      console.log(`${this.name} is ${this.age} year old`)
   },
}
person.printPerson();
Output: Ayushi 😎 is 27 year old.

In the above code, 'this' is referring to the person's object. The printPerson() function is called through the object person, therefore the current execution context is set in the scope of 'person' object.

A constructor:

When you use 'this' keyword in your class or function constructors, A copy of constructor for every calling object is get created.

class person{
  constructor(name, age) {
    this.name = name
    this.age = age
  }

person1 = new person("Divaksh🧑", 30)
person2 = new person("Ayushi👧", 27)

console.log(person1.name + " is " + person1.age + " years old.")
console.log(person2.name + " is " + person2.age + " years old.")
Output:
Divaksh🧑 is 30 years old.
Ayushi👧 is 27 years old.

Explicit Binding

Explicit binding happens with the help of functions like bind(), apply(), call(). These functions act as accessories for 'this' keyword and enhances the functionality of it.

bind()💞:

Shakespeare once said that what is in the name. But I say there is a lot in the name when it is in the context of programming. bind() is used to bind💞 a function to an object. For example,

var fruitBucket = {
    name:'Apple🍏',
    quantity:35,
    getInfo(){
        return "You have "+  this.quantity + " " +this.name
    }
}
var takeOut = function(quantity){
    this.quantity = this.quantity - quantity
    console.log(this.getInfo());
}
var bucketInfo = takeOut.bind(fruitBucket);
bucketInfo(0);
bucketInfo(20);
Output:
You have 35 apple🍏.
You have 15 apple🍏.

Explanation:

When we used bind() function to bind the takeOut() to fruitBucket object, it bound them both and created a new function. Now the new function has permissions to access and modify the values of fruitBucket object attributes with the help of 'this' keyword. From now on for this new function, 'this' keyword will always have reference to fruitBucket object, until you bind it with some other object.

call()🗣️ and apply()🔗:

call() and apply() functions are also do the binding but they allow us to send additional arguments. When we use these functions, a new function is not created instead the original function gets bound with the object. For example, call() can be used in this way.

var zoo = {
   name: 'monkey🐒',
   number: 3
}

function getData(city, year){
   console.log(`There are ${this.number} ${this.name} in ${city} zoo since ${year}`)
}

getData.call(zoo, "London", "1999");
Output:
There are 3 monkey🐒 in London zoo since 1999

apply() is also used in almost same way, except you can send multiple arguments through an array in it. Let's see

var zoo = {
   name: 'monkey🐒',
   number: 3
}

function getData(city, year){
   console.log(`There are ${this.number} ${this.name} in ${city} zoo since ${year}`)
}

getData.apply(zoo, ["London", "1999"]);
Output:
There are 3 monkey🐒 in London zoo since 1999

Hope today I cleared all the doubts and confusions about this, bind apply and call in JavaScript. Feel free to comment below to share views on it.