简体   繁体   中英

How to override class arrow function method

I know this is something simple but I can't seem to find an answer to my question.

Many references that if you have the same function name only the last instance of the function will be called when the function is called (override).

I can't seem to do this if the function is an arrow function.

Normal function behavior:

 class A { constructor() { this.something(); } something() { console.log('I am A'); } } class B extends A { something() { console.log('I am B'); } } let b = new B(); 

This does overrides the something() function in class A but I can't seem to override function something() if it is in an arrow function format.

 class A { constructor() { this.something(); } something = () => { console.log('I am A'); } } class B extends A { something = () => { console.log('I am B'); } } let b = new B(); 

Why is the output of the two are different? How can I override the arrow function in the parent class correctly?

class A {
  constructor() {
    this.something();
  }

  something = () => {
    console.log('I am A');
  }
}

class B extends A {
constructor() {
    super();
    this.something();
  }
  something = () => {
    console.log('I am B');
  }
}

let b = new B();

This works for me. What is happening is that you're calling this.something() inside of Class A, therefore it will use its own method in Class A. If you call this in class B, it will use it own constructor which overrides Class A constructor. You can also call Class A in Class B by using super.something();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM