![](/img/trans.png)
[英]How to extend a class property inherited from parent class in ES6?
[英]ES6: access to inherited class'es properties and methods from the parent class
ES6没有抽象方法或属性,但是我可以从继承的类中获取父类中的某些方法或属性吗?
class ParentClass {
constructor(){
ParentClass.checkClildPropertyAccessibility();
ParentClass.checkClildMethodAccessibility();
ParentClass.checkClildStaticPropertyAccessibility();
ParentClass.checkClildStaticMethodAccessibility();
}
static checkClildPropertyAccessibility() {
console.log(ParentClass.childProperty);
}
static checkClildMethodAccessibility(){
ParentClass.childMethod()
}
static checkClildStaticPropertyAccessibility(){
console.log(ParentClass.childStaticProperty);
}
static checkClildStaticMethodAccessibility(){
ParentClass.clildStaticMethod()
}
}
class ChildClass extends ParentClass {
constructor(){
super();
ChildClass.childProperty = 'child\'s Property: OK';
}
childMethod(){
console.log('child\'s method OK');
}
// static property emulation is ES6
static get childStaticProperty() { return 'Child\'s static property: OK even ES6' }
static clildStaticMethod (){
console.log('Child\'s static method: OK');
}
}
let childClassInstance = new ChildClass();
这个概念是“我们必须在子类中定义一些属性和方法,但是父类需要它们已经在构造函数中使用”。
可以在父类中将当前构造函数在静态方法中引用为this
,在实例方法中将其引用为this.constructor
。
这会导致潜在的设计问题,因为ParentClass
没有在ChildClass
中定义的方法和属性,并且当调用不存在的childMethod
时, new ParentClass
将导致错误。
是的 ,可以调用仅在ES2015类的子类中定义的方法。
class ParentClass { constructor() { this.childMethod(); this.initialize(); console.log(this.childProperty1); console.log(this.childProperty2); } } class ChildClass extends ParentClass { constructor() { super(); this.childProperty1 = 'child\\'s Property: OK'; } initialize() { this.childProperty2 = 'child\\'s Property 2: OK'; } childMethod() { console.log('Child\\'s overriden method: OK'); } } let childClassInstance = new ChildClass();
请注意, initialize()
用于为childProperty2
分配初始值。 父构造函数将始终在子类构造函数中的任何其他代码之前运行,这就是为什么childProperty1
控制台调用时未初始化childProperty1
的原因。 在父类中, this
将指向具有子类prototype
的对象。 在注释部分中, Bergi
指出应该避免在父构造函数中调用重写方法的做法,因为重写方法可能取决于子构造函数尚未设置的状态。
不 ,它不适用于静态方法。 即使将静态方法复制到子类中,当您引用ParentClass
,也会在此处获得定义的方法。 那里没有原型链可循。
编辑 : 从评论部分澄清。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.