【问题标题】:ES6 access functions from child class来自子类的 ES6 访问函数
【发布时间】:2016-07-29 07:57:31
【问题描述】:

鉴于以下代码,我如何从Parent 类访问bar()

class Parent{
    constructor(){

    }

    foo(){
        this.bar() // not defined
    }
}

class Child extends Parent{
    constructor(){
        super();
    }

    bar(){

    }
} 

【问题讨论】:

  • Parent 类对扩展它的Child 一无所知。
  • @DmitriPavlutin 但那是......伤心。无论如何谢谢你:)
  • 值得一提的是,孩子对父母一无所知
  • 但是扩展孩子反而很奇怪xD哈哈。 @MarkoMackic

标签: javascript class ecmascript-6


【解决方案1】:

您确实可以完全按照自己的方式访问它,但是要在 this 上实际定义它,您必须创建一个 Child 实例而不是 Parent 实例:

var c = new Child();
c.bar() // works
c.foo() // calls c.bar() as well

【讨论】:

  • 嗯,是的,这是有道理的,我认为我的问题是错误的,对不起。我需要的确切用例是在 Parent 类中使用它。抱歉,我再次更新了问题。
  • @TheGreenFoxx:如果您在Parent 实例中需要bar,那么您应该在Parent 类中声明该方法。虽然可以直接引用Child.prototype.bar,但它在Parent 中的使用将违反所有良好实践和设计原则。
猜你喜欢
  • 2017-06-28
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 2018-10-14
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多