What is this?
When does the context of this get determined?
Jane Costa, the this queen, told me that this is like a migratory bird. It flies from context to context, changing its value based on its environment. Here is the this bird. It’s going to fly through some different this contexts with us.
Rules of this
1. Default Binding Rule
The first rule of this is the Default Binding Rule. This rule states that if this is used out in the open, outside of any specific object, it is bound to the global context. This means that this holds the value of the global object. For example, this typed straight into the chrome console is the window because the window is the global object of the browser.
NOTE: When this is used outside of any object, strict mode defines this as undefined instead of global to help make visible a potential silent error in your code.
2. Implicit Binding Rule
The second rule of this is the Implicit Binding Rule. This rule states that if this is called within a method of a specific object, the value of this is that specific object.
3. Explicit Binding Rule
The third rule of this is the Explicit Binding Rule. This rule states that when this is assigned by bind( ), call( ), or apply( ), the value of this is the object passed as the first parameter.
4. New Binding Rule
The fourth rule of this is the New Binding Rule. This rule states that when the new keyword is used (in a constructor function) this refers to the newly created object.
What about ARROW FUNCTIONS?
Usually we can assume this is a migratory bird, changing its value based on its environment as it flies from context to context. However when used in an arrow function, this is a turtle, carrying with it its environment (its shell) from where it was defined. This is the this turtle, carrying its this shell from where it is defined wherever it goes.
Check out these charts I made if you want a quick this refresher.