Last week I started writing about how JS is working under the hood by covering the concept of execution context. One component of execution context that I briefly mentioned is the ‘this’ keyword. This seems to be a concept that has confused many developers, myself included. I know myself as well as my cohort mates in bootcamp struggled to grasp the idea of it so I am going to shed some light on the subject. With this edition of ‘JS Under The Hood’ I will be covering ‘this’ and how it is used.
In the simplest explanation possible, ‘this’ refers to the object executing the current function(execution context). Let’s look at some examples to make this clearer.
When talking about ‘this’ inside methods, which are functions stored as object properties, this refers to the object containing the method. Let’s take a look:
Here we have an object, “obj” and our listPets() method inside where we are console logging the keyword this to see its value. From our definition above, ‘this’ should be equal to our “obj” object since it is the object that is executing the method.
When talking about regular JS functions sitting on their own, outside of objects, ‘this’ is going to refer to the same value every time: the Global Window. Since the function is lexically sitting on its own, the object that is executing the function has to be the global one! Let’s take a look.
In my lat blog about execution context I mentioned the global object which is the browser window. As we can see here, ‘this’ in a function will refer to the global window.
Object Constructor Functions
The last context were are going to discuss is ‘this’ in object constructors. When using this in object constructors, ‘this’ will refer to the object created, not the global window even though it is a stand alone function. The “new” operator creates a new object and sets “this” to that object. Let’s check it out in code:
Here we can see that this, is referring to the Song object we just created because that object now owns ‘this’.
Be sure to check out the MDN docs to learn more.