'This' can be confusing
The keyword this is something I have found confusing from the get-go. Often it just doesn't seem to follow an intuitive pattern. For starters, this isn't necessarily bound to the function it appears within - just like any function argument, it could have a different binding each time the function is run.
There are only five ways that this can appear in executing code, each associated with a specific rule that dictates what this is bound to at run time. How can we figure out which rule to apply?
1. Open the debugger. Pause on a line that refers to this.
2. Scan outward to the closest containing function and look a level down into the call stack to where the function was called.
3. Take a look at the syntax of the function call to see which run pattern is in effect:
1. If this appears by itself and isn't enclosed within a function declaration, the run pattern is called a global reference, so the binding target is going to be the global object (i.e. the window in a browser).
2. If this appears within a function declaration the run pattern is called a 'free function invocation', again with the binding target of the global object.
Note: for both of these run patterns the binding target is the global object because when there is no object-associated method being run, the language still has to bind this to something. So while it may not be useful, this is bound to the only object available for consistency's sake.
3. If .call or .apply are used to invoke a function, the binding target is the first argument to call / apply.
4. For a standard method invocation (i.e. target.methodName()), the object on the left of the dot is the binding target.
Note: when a function is invoked with the keyword *new in front, it will execute in the context of a newly created object to use as an instance of a class (i.e. it's presumed to be a constructor function).*
In Summary
When inside a function, the keyword this will be bound to the object that was tot he left of the dot where that function was called.