What is ‘This’ keyword in Javascript?

In Javascript ‘this‘ refers to an object in the current executing context.

Now, let’s check what the hell is the current execution context. It simply means on what scope or environment it is being executed in. Therefore the value of this would change when the execution context is changing.

For example: In the case of the browser this would refer to the window object.

Value of “this” in the browser

Whereas in NodeJs environment it would refer to an object called global. This global object is available in all modules. So, you don’t have to explicitly include these objects in your Nodejs application but rather use them directly.

Value of this in Nodejs environment

In case of a constructor (The function responsible to create a new object) the value of this would then refer to the newly created object.

Value of this when called inside a constructor

As, you could see the getValue function simply prints out the newEmployee object as the value of this. Read more about call here .

In a Node module, this is equivalent to module.exports.

Arrow Functions and value for this

Now, In arrow functions the value for this would be that of the outer scope i.e., the context in which the arrow function was defined. This means that arrow functions do not redefine the value for this. The value for this in arrow functions is in the lexically enclosing context(the context in which the owner of the arrow function was declared/created). Which means that this keyword here represents the scope or the object which defined the arrow function.

Let me explain this with a quick example

function scope(){
    this.randomDetail ="x"
    let Person = {
        name:"XYZ",
        gender: "male",
        age: "20",
        getDetails:_=>{
             console.log("Inside Arrow Function",this)
        },
        getDetails2:function () {
            console.log(this)
        }
}
Person.getDetails()
Person.getDetails2()
}

As you could see our regular function returned the object in the current context as the value for this. While the arrow Function returned us the global object with random Detail as an additional property which we define in our function as the value for this. The reason as mentioned is the same as mentioned before

It’s defined by the lexical environment in which the function was created, which means this value where we created the Person object be this value of the function.

Now that you understand what this keyword refers to Be sure to understand the call apply and Bind Methods as these methods are used to set custom values for this. Link to the Blog: here

Leave a Reply