In JavaScript, “this” will refer to the execution context for that specific call.
When we invoke a function, an execution context is created. This execution context is basically a record of information that is important to our function. It lets us know where the function was called from, the parameters that were passed etc. One of the most important properties the record saves is "this" reference which will be used during the function's execution.
Well, in order to determine this, we will need to find exactly where our function was called from. Once we find the location, there are some rules that are applicable.
When a function is invoked with the new keyword, "this" will reference the newly created object:
When a function is invoked with the dot notation, "this" will reference the object to the left of our dot:
Uses call, apply and bind functions to explicitly provide value of "this". These methods allow a method that was defined for one object, to be assigned and called by another object.
Thus explicitly providing the value of "this":
The main differences between the three aforementioned methods used for explicit binding are the following:
Undefined in strict mode, otherwise the global object — even if used within a function:
When using event listeners, the object being listened to will be bound to "this":
Arrow functions bind this lexically. Since they don't have their own context in which they execute, "this" get inherited from the parent function: