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

this keyword

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 scope
  • jonas is the owner of calcAge not because it is written in jonas, but because jonas is the one calling it
  • then we copy calcAge to matilda (called method borrowing) and now it is also contained in the matilda object
    • this keyword
  • we copy calcAge from jonas to const f and then we look at it in the console --- it is the same function
    • this keyword
  • when we call f, this is undefined because it haas no 'owner anymore'
    • this keyword

this in Regular Functions vs. Arrow Functions

  • Example 1: this in the regular function is undefined, while in the arrow function it is the window object
    • this keyword
  • Example 2:
    • we add a firstName property and another method to the jonas 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 --- the this in greet() is the global this (on the window object)
    • the window object doesn't have a firstName property so that is undefined as well
    • this keyword
    • now we use var to create a firstName property on the window object, so this is no longer undefined
    • this keyword
      • Best Practices (according to Jonas): try not to use var and never ever use an arrow function in a method (even if not using the this keyword)
    • now with a regular function jonas is this
    • this keyword
    • then we add the regular function isMillenial inside the calcAge method and call it from within calcAge --- this is undefined because it is a regular function call even though it is inside a method
    • this keyword
    • can use an extra variable , usually called self or that to get around this being undefined in isMillenial --- this was the pre-ES6 solution
    • this keyword
    • 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)
    • this keyword

Copyright © 2022