NOTE: All images from Jonas Schmedtmann's The Complete Javascript Course 2020
NOTE: There are more notes about this subject from another course here
The this
Keyword
Code Examples
this
in Objects
jonas
is an object literal (a way we literally define objects), not a code block, so it doesn't get its own scopejonas
is the owner ofcalcAge
not because it is written injonas
, but becausejonas
is the one calling it- then we copy
calcAge
tomatilda
(called method borrowing) and now it is also contained in thematilda
object - we copy
calcAge
fromjonas
toconst f
and then we look at it in the console --- it is the same function - when we call
f
,this
is undefined because it haas no 'owner anymore'
this
in Regular Functions vs. Arrow Functions
- Example 1:
this
in the regular function is undefined, while in the arrow function it is thewindow
object - Example 2:
- we add a
firstName
property and another method to thejonas
object used above - when we call the new arrow method that was added, we get undefined --- an arrow method doesn't get its own
this
--- thethis
ingreet()
is the globalthis
(on thewindow
object) - the
window
object doesn't have a firstName property so that is undefined as well - now we use
var
to create a firstName property on thewindow
object, sothis
is no longer undefined - Best Practices (according to Jonas): try not to use
var
and never ever use an arrow function in a method (even if not using thethis
keyword)
- Best Practices (according to Jonas): try not to use
- now with a regular function
jonas
isthis
- then we add the regular function
isMillenial
inside thecalcAge
method and call it from withincalcAge
---this
is undefined because it is a regular function call even though it is inside a method - can use an extra variable , usually called
self
orthat
to get aroundthis
being undefined inisMillenial
--- this was the pre-ES6 solution - the ES6 solution is to use an arrow function (while we don't want the method to be an arrow function...a
function within the method can be an arrow function to preserve the parent scope's
this
)
- we add a