In this tutorial, we will look at the
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.
the object-oriented world into JS. And we know that a functional programming language doesn't have
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 inheritance by leveraging the prototype model. Although you might say that ES6 has classes, it is nothing but syntactic sugar over the prototype system.
ES6 classes are just syntactic sugar over the Prototype Model.
With all that being said,
this keyword is a very easy concept to understand, and let me show you
Why Do We Need THIS
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 the
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
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 how we reach that conclusion is important too.
'this' is a run-time binding and not an author-time binding.
Rules for Call Site
- Default Binding
- Implicit Binding
- Explicit Binding
- new Operator Binding
- Arrow Functions
In the next part, we will see how Default Binding works. By the way, I have covered these posts on my youtube channel as well.