DEV Community

Discussion on: Master ‘this’ in JavaScript

Collapse
 
polymathsomnath profile image
Somnath Singh

Namaste @kumarutsav ,
Thank you so much for your response!

The "this" object inside an arrow function is lexically bound, which is just a fancy way of saying its value is static and determined by the place where the “this" keyword is defined.

I have used the word lexical here, the word ‘lexical’ means having to do with words or grammar. It deals with where something sits physically in your code that you write.

You see the CS people have a fancy for naming terms so that they sound extra-terrestrial. Lexical just means where to you see it. I can say your fingers are lexically bound to your palm! Do you get what I am trying to say?

So let me ask you a question, where do you see this in the code that has an arrow function? Inside the setInterval function right? We can see the setInterval is inside the start function. So we can say it is a sub-function.

In another case, we saw that once we use this inside a sub-function it is bound to the global object. This happens because, in JavaScript, functions started as a method to the global scope object in our case that is the window object.
This is how the language is designed @kumarutsav . Many feel it is a bug--don't forget the language was designed in 10 days.

This is just the opposite of what one might expect, you use this inside a function in an object and, it works! But the moment you use it inside a sub-function in an object it does not.
So the arrow function that came in ES6 is meant to clear these problems up.
The this in arrow function will bound to the object even if you use it in a sub-function. We no longer need to cache a reference like var self = this as we did in one example.

I hope it clears your doubt! If it does not, then please let me know

Collapse
 
kumarutsav profile image
Kumar Utsav

My query was not regarding the lexical scoping but about the determined by the place where the “this" keyword is **defined**. How are you defining this keyword?

Thread Thread
 
polymathsomnath profile image
Somnath Singh • Edited

You are not defining the this keyword @kumarutsav , You are making use of it!
The statement just further explains what lexical scoping means.
Read once again, they are connected. 😉