this, call, apply, bind in JavaScript A-Z

this, call, apply, bind in JavaScript A-Z

this keyword is very important and might be a confusing topic in JavaScript. I will try to explain this topic with all possible examples.

Why is this used in JS? In normal words, this is pointed an object. Which object depends on how this is being invoked.

Now, Jump to the code and try to understand more deeply.

const person = {
    name: "sumon",
    age: 23,
    height: "medium",
    iqueue: function () {
        console.log(`${this.name} iqueue is very low`);
    }


}

person.iqueue();

Here this.name can create confusion, what is this referred to? You have to notice where the function called, here person.iqueue() invokes this. Now, notice this line of code person.iqueue(). this referred to the person object here.

const person = function (name, age) {
    return {
        name: name,
        age: age,
        iqueue: function () {
            console.log(`${this.name} iqueue is very low`);
        },
        friends: {
            name: "sumon",
            findFriends: function () {
                console.log(`His friend is ${this.name}`);
            }
        }

    }
}

var details = person("sahed", 23);
details.iqueue();
details.friends.findFriends();

Let's think about what will be output for details.iqueue() and details.friends.findFriends(). What is this referred to for both cases. Just look before the ., you will find your answer. That's means, this for iqueue function pointed to the person name and find friend's this pointed to the friend name.

Now, discuss some others scenarios. What if the function is in the local scope.

var iqueue = function () {
    console.log(`${this.name} iqueue is very low`);
}

const person = {
    name: "sumon",
    age: 23,
    height: "medium",
}

iqueue.call(person)

Now, we can't call the function like before. So, we can use .call(). .call() is referred to the this. .call() can recive two perameter, this and value.

var iqueue = function (friendName) {
    console.log(`${this.name} and ${friendName} iqueue is very low`);
}

const person = {
    name: "sumon",
    age: 23,
    height: "medium",
}

var friendName = "sahed"

iqueue.call(person, friendName)

Here, this referred to the person and friendName is the value. Value can be more than one. iqueue.call(person, friendName,a,b,c)

There is a concept almost the same as .call(). This is .bind(). It works the same but doesn't immediately call the function. You can call it when you needed.

ar iqueue = function (friendName) {
    console.log(`${this.name} and ${friendName} iqueue is very low`); //sumon and //sahed iqueue is very low
}

const person = {
    name: "sumon",
    age: 23,
    height: "medium",
}

var friendName = "sahed"

var info = iqueue.bind(person, friendName)

info();

Let's assume the friend's name is an array. Then we should use .apply(). It only accepts two parameters, this and array.

var iqueue = function (n1, n2, n3) { //call all values
    console.log(`${this.name} and ${n1} ${n2} ${n3} iqueue is very low`);
}

const person = {
    name: "sumon",
    age: 23,
    height: "medium",
}

var friends = ["sahed", "suvom", "mona"]


iqueue.apply(person, friends)

Try to understand another example of this.

function Person(name, age) {
    this.name = name;
    this.age = age;
    console.log(`${this.name}'s age is ${this.age}`);

}

var karisma = new Person("karisma", 29)

Here this referred to which object? person function is a constructor function. That's mean it creates a null object this in the function when we call the function with the new keyword.

function Person(name, age) {
    //let this = object.create(null);
    this.name = name;
    this.age = age;
    console.log(`${this.name}'s age is ${this.age}`);
    //return this
}

var karisma = new Person("karisma", 29)

According to this example this doesn't point to var karisma directly. It points to the null object, creates attributes, and returns the object under the hood.

I will end this blog with an interesting example. Guess the out of the bellow code.

var profession = function () {
    console.log(this.name);
}


profession();

The output of this code is undefined. But if you notice this.name is not valid. But there is no error, Why? Because JavaScript is a smart language. Here this pointed the global window. You will better understand from this code.

var profession = function () {
    console.log(this);
}


profession();

Now check the browser console. you will find the window in the browser console.

Hopefully, understand this topic clearly. Happy Coding 👨‍💻