this keyword. The
At first determining the value of
this might feel a little like magic and have you throwing
console.log()'s in your code. However, there are only a few rules that you can go through to figure out what
this is referring to. The most important thing to first remember is that the value of
this depends on how a function is called. Looking at where the function is defined will not help you.
First we look to see if the
new keyword is used when calling the function. If
new is used
this inside the function will refer to the brand new object created when
Object.Create() under the hood.
Second we see if apply, call, or bind are used when calling the function.
this inside the function will refer to the object that is passed in as the argument to apply, call, or bind.
Third, if a function is called as a method, such as obj.method() —
this will refer to the object that the function is a property of.
this is the global object. In a browser, it is the
window object. If in strict mode (
this will be
undefined instead of the global object.
One thing to note is that ES6 arrow functions ignore all the rules above. They do not have their own
this is referring to.
If we think about why we write functions in general we see that functions make it easy to encapsulate and reuse logic. The
this keyword lets us decide what context we want when we invoke a function. By using
this we can reuse functions or methods within different contexts or with different objects.