In this tutorial, we will look at
this keyword and break it down into five parts so that each part is bite-sized and easy to comprehend. By the end of this series, you will have a super solid intuitive mental model that will stay with you for the longest time.
this keyword, but object-oriented programming does.
Even though JS decided to mimic the look and feel of Java, from within, JS is very much like Scheme. It does not implement a true object-oriented system, but JS achieves inhertiance by leveraging the prototype model. Although you might say that ES6 has classes, and it is nothing but syntactic sugar over the prototype system.
ES6 classes are just a syntactic sugar over the Prototype Model.
With all that being said,
this keyword is very easy concept to understand, and let me show you how.
One way you can see this keyword is as a way to do a 2-dimensional look up in your scope. When you define a variable, the lookup in your scope chain happens from inner to outer functions until you reach the global scope. Now, what if you want one of your variables to look up for data/or-its-value in other parts of your scope?
this keyword gives us a way to solve it. And there is much more to
this which we will see in the next part of the series.
Now, you could say that, I could write a function and receive an argument as my data. And you wouldn't be wrong, but that's just another way to solve it.
Call site refers to the location of the function invocation, and it is an important step in determining what the value of
this keyword is going to be. In some cases, the call-site can get hidden away by libraries and native APIs, e.g., setTimeout, but those cases are limited and predictable.
There is an informal rule that says, whatever is on the left is what this keyword points to. It's a good conclusion to some extent, but nevertheless, how we reach that conclusion is important too.
'this' is a run-time binding and not an author-time binding.
new operator Binding
& then you have your arrow functions. And the value of
this keyword is determined by those five ways.