JS如何知道子类是否覆盖父方法

时间:2019-03-22 04:56:36

标签: javascript

比方说,我有一个超类和一个重写超方法之一的孩子。

class Test {

  doSomething() {
    callsomething({
      callback: this.method
    })
  }

  method() {
    console.log('parent');
  }
}

class A extends Test {
  constructor() {
    super();
  }

  method() {
    console.log('override');
  }
}

new A().method(); 

有一种方法可以在Test类中知道method是否被覆盖?

1 个答案:

答案 0 :(得分:3)

doSomething内,检查this.method是否引用了Test.prototype.method-如果不是,则this.method引用了其他内容,这意味着它已经被遮盖了,很可能通过子类方法:

class Test {
  doSomething() {
    if (this.method === Test.prototype.method) {
      console.log("Method is native Test's!");
    } else {
      console.log("Method is not Test's, it's been shadowed!");
    }
  }

  method() {
    console.log('parent');
  }
}

class A extends Test {
  constructor() {
    super();
  }

  method() {
    console.log('override');
  }
}

new A().doSomething(); 
new Test().doSomething(); 

您还可以在Test的构造函数中进行相同的检查:

class Test {
  constructor() {
    if (this.method === Test.prototype.method) {
      console.log("Method is native Test's!");
    } else {
      console.log("Method is not Test's, it's been shadowed!");
    }
  }
  method() {
    console.log('parent');
  }
}

class A extends Test {
  constructor() {
    super();
  }
  method() {
    console.log('override');
  }
}

new A()