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

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

但是,some_class_property 在 superclass 构造函数中被放置到 实例化对象本身 中(好吧,在 class 字段中,这实际上是将它放到 superclass 构造函数中的对象上的语法糖),这意味着您可以通过引用 this.some_class_property 在子 class 中引用它。您没有引用隐藏方法或 属性,因此不需要 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 returns 数组的新长度,这就是为什么上面代码片段的结果是 4。 (如果您想复制 some_class_property 数组,无论出于何种原因,请改用 some_class_property = [...this.some_class_property, 4]

使用super的时候是子实例上存在一个属性,或者子原型,但是你想在父原型上引用一个属性,eg :

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();

Public 和私有属性是 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(){...}
}