【问题标题】:How to call the root class methods of a javascript object?如何调用 javascript 对象的根类方法?
【发布时间】:2018-03-20 06:19:15
【问题描述】:
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...')}
}

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

我试过了:

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

但我得到了错误:

未捕获的类型错误:无法读取未定义的属性“walk”

【问题讨论】:

  • 你可以试试 -> Animal.prototype.walk.call(c)
  • Animal.prototype.walk() 如果你想在子类的上下文中调用它Animal.prototype.walk.call(c)
  • @Keith ,塔哈:那行得通。非常感谢

标签: javascript oop inheritance super


【解决方案1】:

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

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

Keithtaha 推荐

【讨论】:

    【解决方案2】:

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

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

    如果你想从你的Cat 类调用Animal 类的walk() 方法,不要在你的Mammal 类中覆盖它。这将允许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...'
      }
    }
    

    【讨论】:

    • 这会调用 Mammal 的 walk() 方法。我想绕过它并调用 Animal 的 walk() 方法。谢谢!
    • 你为什么要这样做?
    • @Naveen 我已经更新了解释超级链接的答案,但你真的不应该通过正确的 OOP 继承来做到这一点。
    • 实际上,Mammal 的 walk() 方法会打印“哺乳动物行走..”,如果我执行 super.walk(),它会打印“动物行走... Mammel walk..”。我只想打印“动物行走...”。 super.super.walk() 说 Cannot read property 'walk' of undefined
    • @Naveen 我已经根据你告诉我的内容再次更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2016-09-10
    • 2011-04-01
    • 2017-11-04
    • 1970-01-01
    • 2014-03-08
    • 2020-05-03
    相关资源
    最近更新 更多