2016-07-29 56 views
1

给定下面的代码,如何访问Parent类中的bar()来自子类的ES6访问函数

class Parent{ 
    constructor(){ 

    } 

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

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

    bar(){ 

    } 
} 
+1

'Parent'类不知道任何关于延伸它的“孩子”。 –

+0

@DmitriPavlutin但这是...悲伤。反正谢谢:) – CENT1PEDE

+0

值得一提的是,孩子知道所有关于父母 –

回答

0

你做你确实做到了访问,但为了能在this实际定义,你必须创建一个Child实例不是Parent之一:

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

嗯,这是有道理的,我认为我的问题是错误的,对不起。我需要的确切用例是在'Parent'类中使用它。我再次更新了这个问题。 – CENT1PEDE

+0

@TheGreenFoxx:如果你在'Parent'实例中需要'bar',那么你应该在'Parent'类中声明该方法。虽然可以直接引用'Child.prototype.bar',但它在'Parent'中的用法将违背所有良好实践和设计原则。 – Bergi