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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我可以在ES6中扩展类覆盖基类属性吗?相关的知识,希望对你有一定的参考价值。

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

答案

如果传递了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();

以上是关于我可以在ES6中扩展类覆盖基类属性吗?的主要内容,如果未能解决你的问题,请参考以下文章