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

时间:2018-02-28 19:07:32

标签: javascript oop ecmascript-6

我正在寻找以下内容,纯粹使用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可以实现吗?我读过/尝试的所有东西都指向基础构造函数的上下文,它是用它初始化的。

1 个答案:

答案 0 :(得分: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();