如何调用 javascript 对象的根 class 方法?

How to call the root class methods of a javascript object?

class Animal{
  constructor(){...}
  walk(){ console.log('Animal walking...')}
}

class Mammal extends Animal{
  constructor(){...}
   walk(){console.log('Mammal walking...')}
}

class Cat extends Mammal{
  constructor(){}
  walk(){console.log('Cat walking...')}
}

在上面的 class 层次结构中,我想从 Cat 对象调用 Animal 的 walk() 实现

我试过了:

class Cat extends Mammal{
  constructor(){}
  walk(){
     super.super.walk()
  }
}

但我收到错误消息:

Uncaught TypeError: Cannot read property 'walk' of undefined

您不能从实例外部调用 super,只能从进行继承的 class 内部调用。

class Cat extends Mammal {
  walk() {
    super.walk()
  }
}

如果您想从 Cat class 中调用 Animal class' walk() 方法,请不要在 Mammal class。这将允许 MammalAnimal.

继承 walk()
class Animal {
  walk() { console.log('Animal walking...') }
}

class Mammal extends Animal {
   // don't override walk if you don't have to
}

class Cat extends Mammal {
  walk() {
    super.walk() // will print 'Animals walking...'
  }
}

Cat 调用 Animal 的 walk() 方法,绕过 Mammal 的 walk()

class Cat extends Mammal{
  walk(){
     Animal.prototype.walk.call(this)
  }
}

Keith and taha

建议