javascript - ES6中如何扩展从父类继承的类属性?

标签 javascript es6-class

我有以下代码:

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/

相关文章:

javascript - 如何在 Javascript 类定义内部(外部)定义原型(prototype)方法?

javascript - Ajax - 通知 : Undefined index: id

javascript - 搜索机制在 Html 表中不起作用

javascript - 如何将这个 IIFE 重写为 ES6 类?

javascript - 全局初始化 Javascript 类

javascript - 异步代码运行 - 在react-native中使用Javascript OOP

javascript - 访问 ES6 类中静态 setter 中的类数据

javascript - 如何管理大型 JavaScript 数据文件?

javascript - jQuery 菜单不起作用,即(文档模式 : Quirks)

javascript - react-native-maps:UrlTile 和 Polyline - zIndex/Overlaying 不工作