-2

I have two classes. The class Two must extend from One. Both have method with the same name which do different console.logs. How to first console.log ('Hey from class One!') and then console.log('Hey from class Two!') by calling newTwo.hey()? I only get 'Hey from class Two!';

class One{
  sayHey() {
   console.log('Hey from class One!');       
  }
}

class Two extends One{
  constructor() {
    super();
}
  sayHey() {
   console.log('Hey from class Two!');       
  }
}

const newOne = new One();
const newTwo = new Two();
newTwo.sayHey();
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
brad_fresh
  • 129
  • 1
  • 11
  • 2
    Does this answer your question? [How to call a parent method from child class in javascript?](https://stackoverflow.com/questions/11854958/how-to-call-a-parent-method-from-child-class-in-javascript) – Anurag Srivastava Apr 16 '20 at 09:42
  • @Anurag Srivastava No. Viktor W answered my question. – brad_fresh Apr 16 '20 at 09:58
  • 1
    :) Maybe if you could read the [answer](https://stackoverflow.com/a/41346510/7867822) in the link properly, you would find what you're looking for, but whatever suits you – Anurag Srivastava Apr 16 '20 at 10:00

1 Answers1

2

The sayHey implementation in class Two overrides the sayHey method of the parent class, which means that only the child implementation gets called. You can access the parent using the super keyword, and call the method using that.

class Two extends One {
    sayHey() {
        super.sayHey()
        console.log(...)
    }
}
Viktor W
  • 1,139
  • 6
  • 9