The "this" keyword always refers to an object, but the value of "this" changes depending on where it is called. When a function is called, an execution context is created that contains a reference to "this". Because the value of "this" changes depending on execution context, we can determine the value of "this" by examining the function's call-site, or where it is called.
When called alone, or within a function, "this" will refer the Global object. In a browser, this will refer to the Window object. One exception to this is if the user is in strict mode, in which case "this" will be undefined.
If a function is contained within an object, "this" will refer to the nearest parent object. Even if the function is only referenced in the object, "this" will still refer to the object.
There are three functions call, bind, and apply that can be used to set the value of "this". Call and apply work largely the same way, the first argument passed to each will be what "this" refers to. Bind actually creates a new function which a permanently assigned "this" value.
When using the new keyword, "this" will refer to the new object that is being created.
One exception to these general rules of thumb is that when using an arrow function, "this" will retain the value of its parent scope.
So a quick summary of the "this" keyword:
- "This" is usually determined by a function's execution context.
- By default, "this" refers to the global object (window object in a browser).
- When the "new" keyword is used, "this" will refer to the new object.
- Call, bind, and apply can be used to set "this" value.
- Arrow functions do not re-bind "this".