this keyword and arrow functions

PHOTO EMBED

Wed Jun 19 2024 02:54:51 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #this #arrow #functions

const shaunObj = {
  name: 'gary',
  year: 1987,
  currentYear: new Date().getFullYear(),

  // solution 1 = declare a normal function as this is bound to these functions
  calcAgeOne: function () {
    const self = this;
    const yearsold = self.currentYear - self.year;
    return yearsold;
  },

  // solution 2
  calcAgeTwo: function () { // declative function again but with arrow function inside
    console.log(this);

    const calcAgeArrow = () => {
      console.log(this);
      const yearsold = this.currentYear - this.year;
      return yearsold;
    };

    return calcAgeArrow(); // return the arrow function to the parent function
  },

	// DO NOT DO THIS
  // calcAge: () => {
  //   const yearsold = this.currentYear - this.year;
  //   return yearsold;
  // },
};

console.log(shaunObj.calcAgeOne());
console.log(shaunObj.calcAgeTwo()); // works with
content_copyCOPY