我有以下代码:
class Parent {
some_class_property = [1,2,3];
some_other_methods(){...}
}
class Child extends Parent {
some_class_property = super.some_class_property.push(4);
}
控制台给我一个语法错误,说关键字 super
是意外的。
如果 ES6 中允许类属性,那么不允许在子类中扩展它有什么意义呢?如果这不是正确的方法,那么该怎么做呢?谢谢。
最佳答案
看起来类字段内不允许使用 super
引用,这就是当前代码抛出错误的原因。
但是,some_class_property
被放在父类(super class)构造函数中的实例化对象本身上(嗯,在类字段中,这是有效的语法糖,用于将其放入父类(super class)构造函数中的对象),这意味着您可以通过引用 this.some_class_property
在子类中引用它。您没有引用隐藏的方法或属性,因此不需要 super
:
class Parent {
some_class_property = [1, 2, 3];
}
class Child extends Parent {
some_class_property = this.some_class_property.push(4)
}
const c = new Child();
console.log(c.some_class_property);
还请记住,.push
返回数组的新长度,这就是上面代码片段的结果为 4
的原因。 (如果您出于某种原因想要复制 some_class_property
数组,请改用 some_class_property = [...this.some_class_property, 4]
)
使用super
是当子实例或子原型(prototype)上存在属性,但您想引用父原型(prototype)上的属性时,例如:
class Parent {
method() {
console.log('parent method');
}
}
class Child extends Parent {
method() {
console.log('child method');
}
invokeParentMethod() {
super.method();
}
}
const c = new Child();
c.method();
c.invokeParentMethod();
关于javascript - ES6中如何扩展从父类继承的类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58281859/