我可以在ES6中扩展类覆盖基类属性吗?

问题描述 投票:0回答:1

我正在寻找以下内容,纯粹使用ES6 / JS:

class ParentClass {
    prop = true;
    constructor() {
        console.log("Prop is", this.prop);
    }
}

class ChildClass extends ParentClass {
    prop = false;
    constructor() {
        super();
    }
}

const childClassInstance = new ChildClass();

//

"Prop is false"

这可能与ES6有关吗?我读过/尝试过的所有内容都指向基础构造函数的上下文,它是初始化的内容。

javascript oop ecmascript-6
1个回答
0
投票

如果传递了prop param,您可以检查父类,并使用该值或默认的true值。

class ParentClass {
  constructor(prop) {
    this.prop = prop != undefined ? prop : true;
    console.log("Prop is", this.prop);
  }
}

class ChildClass extends ParentClass {
  constructor(...props) {
    super(...props);
  }
}

const one = new ChildClass(false);
const two = new ChildClass();
© www.soinside.com 2019 - 2024. All rights reserved.