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
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter