0

when it comes to this in javascript classes it suppose to refer to the class instances but at somechildmethod() method it don't it throws an error saying TypeError: Cannot read property 'name' of undefined and I know this error will go away if I use the arrow function but I want to know why please!

class parent {
  constructor(name, score) {
    this.name = name;
    this.score = score;
  }
  someparentmethod() {
    console.log("Hi!");
  }
}
class child extends parent {
  constructor(name, score, thirdprop) {
    super(name, score);
    this.thirdprop = thirdprop;
  }
  somechildmethod() {
    return function () {
      console.log(this.name);
    };
  }
}
const child1 = new child("zahal", 1);
const child2 = child1.somechildmethod();
child2();
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
Zahal A_Omer
  • 111
  • 1
  • 7
  • 1
    Everything you need to know about `this` is explained in [How does the “this” keyword work?](/a/3127440/4642212). `child2()` is a contextless call of a `function` function, and `somechildmethod` is within a `class`, which implies strict mode, so `this` will be `undefined`. – Sebastian Simon Jul 31 '21 at 15:06
  • Note that an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `return () => { console.log(this.name); };` *would* work (inherit `this`). – edemaine Jul 31 '21 at 15:17
  • and please read from YDKJS if you have time, https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch2.md – Louay Al-osh Jul 31 '21 at 15:28
  • 1
    @edemaine As the OP already described: _“and I know this error will go away if I use the arrow function”_. – Sebastian Simon Jul 31 '21 at 15:33
  • thank you all I get it. – Zahal A_Omer Aug 01 '21 at 18:37

0 Answers0