繁体   English   中英

如何在 ES6 中扩展从父 class 继承的 class 属性?

[英]How to extend a class property inherited from parent class in ES6?

我有以下代码:

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 中允许 class 属性,那么不允许在子类中扩展它有什么意义呢? 如果这不是正确的方法,那怎么办? 谢谢。

看起来 class 字段中不允许super引用,这就是您当前的代码引发错误的原因。

But, the some_class_property is put onto the instantiated object itself in the superclass constructor (well, in the class field, which is effectively syntax sugar for putting it onto the object in the superclass constructor), which means you can reference it in the child 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的时间是子实例或子原型上存在属性,但您想引用父原型上的属性时,例如:

 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 功能处于实验阶段(ES11?)。 在 ES6 的过去几年里,人们一直在这样做:

class Parent {
    constructor(x){
        this.property1 = [1,2,3];
        ...
    }
    some_other_methods(){...}
}
Parent.property2 = [4,5,6];                 // to access: Parent.property1
Parent.prototype.property3 = [7,8,9];       // to access: obj.property2

class Child extends Parent {
    constructor(x){
        super(x);
        // ...
    }
    some_other_methods(){...}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM