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
jonasis an object literal (a way we literally define objects), not a code block, so it doesn't get its own scopejonasis the owner ofcalcAgenot because it is written injonas, but becausejonasis the one calling it- then we copy
calcAgetomatilda(called method borrowing) and now it is also contained in thematildaobject - we copy
calcAgefromjonastoconst fand then we look at it in the console --- it is the same function - when we call
f,thisis undefined because it haas no 'owner anymore'
this in Regular Functions vs. Arrow Functions
- Example 1:
thisin the regular function is undefined, while in the arrow function it is thewindowobject - Example 2:
- we add a
firstNameproperty and another method to thejonasobject used above - when we call the new arrow method that was added, we get undefined --- an arrow method doesn't get its own
this--- thethisingreet()is the globalthis(on thewindowobject) - the
windowobject doesn't have a firstName property so that is undefined as well
- now we use
varto create a firstName property on thewindowobject, sothisis no longer undefined 
- Best Practices (according to Jonas): try not to use
varand never ever use an arrow function in a method (even if not using thethiskeyword)
- Best Practices (according to Jonas): try not to use
- now with a regular function
jonasisthis
- then we add the regular function
isMillenialinside thecalcAgemethod and call it from withincalcAge---thisis undefined because it is a regular function call even though it is inside a method
- can use an extra variable , usually called
selforthatto get aroundthisbeing 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