In short, this refers to the context that the current scope is referring to. It is literally a pronoun that points to some object (subject) in memory that we possibly want to work with (and very often do) within the scope of the current function invocation.
1) Free Function Invocation (in the browser)
- A free function is one that is just floating around in the global space, not nested within an object or another function.
- In such cases, when we call this function, this is going to evaluate to be the window.
2) Global Execution (in browser)
3) Method Invocation
- this is the object to the left of the dot AT CALL TIME of the function referencing “this”
- What’s going on here is that we have created a ‘shout’ function that references “this” or more specifically “this.message” — We’ve created two objects, ‘amira’ and ‘marcus’ and both of them have ‘message’ properties. When we call ‘shout’ on each of them, in this context, this first refers to amira, and then this refers to marcus. This illustrates a very simple point. When you have a method invocation, this refers to the object to the left of the dot at call time.
4) Constructor Invocation
- this is the brand new instance returned by the constructor
- In this example, we’ve created a constructor called “Food.” Food has the properties this.taste, this.calories, and this.msg — when we create new instances of this constructor, as we did with cookie and banana, we can assign values to those properties by passing them in as parameters. Then, for each Food instance, ‘this’ refers to the individual object that we have created. For cookie, this.taste refers to ‘delicious’ whereas for banana, this.taste refers to ‘decent’ because ‘this’ is bound to the new instance returned by the constructor.
5) .call or .apply invocation
- this is your first argument to call or apply
- There are two extremely useful methods, ‘call’ and ‘apply’ that basically allow you to manipulate what this is referring to. I won’t go into depth of how they can be used here (maybe that will be another blog post) but once you understand how ‘call’ and ‘apply’ work, then you will realize that whatever you pass in as the first parameter is bound to the keyword ‘this’ in the context of the function that you call ‘call’ or ‘apply’ on. In this particular case, you can pass in an empty object or undefined if the function you are working with does not ever reference this.
So those are the five rules for this in a nutshell. If you are ever not sure what this is, just figure out which of the five buckets it falls into, and refer to that! (Or, you can be like me, and just console.log it ;)) Credit to the awesome Phillip Alexander (and Hack Reactor!) for teaching me these concepts.