How "this" works
Determining what this
is actually rather simple. The overarching rule is that this
is determined at the time a function is invoked by inspecting where it's called, its call site. It follows these rules, in order of precedence.
Rules
- If the
new
keyword is used when calling the function,this
inside the function is a brand new object.
- If
apply
,call
, orbind
are used to call a function,this
inside the function is the object that is passed in as the argument.
- If a function is called as a method - that is, if dot notation is used to invoke the function -
this
is the object that the function is a property of. In other words, when a dot is to the left of a function invocation,this
is the object to the left of the dot. (f symbolizes function in the code blocks)
- If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above,
this
is the global object. In a browser, it'swindow
.
Note that this rule is the same as rule 3 - the difference is that a function that is not declared as a method automatically becomes a property of the global object, window
. This is therefore an implicit method invocation. When we call fn()
, it's interpreted as window.fn()
, so this
is window
.
-
If multiple of the above rules apply, the rule that is higher wins and will set the
this
value. -
If the function is an ES2015 arrow function, it ignores all the rules above and receives the
this
value of its surrounding scope at the time it's created. To determinethis
, go one line above the arrow function's creation and see what the value ofthis
is there. It will be the same in the arrow function.
Going back to the 3rd rule, when we call obj.createArrowFn()
, this
inside createArrowFn
will be obj
, as we're calling it with dot notation. obj
therefore gets boudn to this
in arrowFn
. If we were to create an arrow function in the global scope, this
would be window
.
Applying the Rules
Let's go over a code example and apply our rules. Try figuring out what this
will be with the two different function calls.
Determining Which Rule Applies
obj.printThis()
falls under rule 3 - invocation using dot notation. On the other hand, print()
falls under rule 4 as a free function invocation. For print()
we don't use new
, bind/call/apply
, or dot notation when we invoke it, so we go to rule 4 and this
is the global object, window
.
When Multiple Rules Apply
When multiple rules apply, the rule higher on the list wins.
If rules 2 and rules 3 both apply, rule 2 takes precedence.
If rules 1 and 3 both apply, rule 1 takes precendence.