Introduction

this keyword refers to the object that the function belongs to or the object that the function is called on. The value of this is dynamic and changes depending on the context in which it is used.

There are four different contexts in which this is used in JavaScript:

1. Global Context

In the global context, this refers to the global object, which is a window in the browser and global in Node.js.

console.log(this);  // logs the windows object in the browser

function test(){
    console.log(this) // logs the windows object in the browser
}

test();

2. Function Context

const person = {
    name: 'test user',
    sayHi: function(){
        console.log('Hi,my name is '+this.name) // logs: Hi,my name is test user
    }
}

person.sayHi();

const sayHiToUser = person.sayHi;
sayHiToUser();  // logs: Hi,my name is undefined
const person = {
    name: 'test user',
    sayHi: function(){
        console.log('Hi,my name is '+this.name) // logs: Hi,my name is test user
    }
}

person.sayHi();

const sayHiToUser = person.sayHi.bind(person);
sayHiToUser();  // logs: Hi,my name is test user

3. Method Context

const person = {
    name: 'test user',
    sayHi: function(){
        console.log('Hi,my name is '+this.name) 
    },
    address: {
        city: 'Chennai',
        State: 'TN',
        getFullAddress: function(){
            console.log('My address is ' + this.city + ' ,' + this.State)
        },
        getFullAddressWithName: function(){
            console.log('Hi,my name is '+ this.name+ ' And My address is ' + this.city + ' ,' + this.State)
        }
    }
}

person.address.getFullAddress(); // logs: My address is Chennai, TN
person.address.getFullAddressWithName(); // logs: Hi,my name is undefined And My address is Chennai ,TN

4. Constructor Context

function persons (name,age){
    this.name = name;
    this.age = age;
}

const john = new persons('test user',30);
console.log(john.name);// logs: test user

In the above example, this refers to the instance of the Person object being created when the new keyword is used to create a new instance of the Person object.

Conclusion