Typescript防止覆盖子类属性

时间:2017-07-11 02:04:44

标签: javascript inheritance override es6-class

鉴于以下情况:



class Parent {
    propStr = "Hello";
    propNum = 42;

    constructor(propShared) {
        console.log(this.propStr); // Hello
        console.log(this.propNum); // 42
        console.log(this.propShared); // w/e
    }
}

class Child extends Parent {
    propStr = "Hi"; // overridden
    propNum = 1337; // overridden

    constructor(propShared) {
        super(propShared);
    }
}

let c = new Child("Foobar");




如何确保正确覆盖父属性,以便console.log打印子属性?

1 个答案:

答案 0 :(得分:2)

您正在父构造函数中记录属性,它们尚未super()之后运行的子构造函数代码覆盖。您应该只在构造函数中进行初始化,而不是执行任何副作用:

class Parent {
    propStr = "Hello";
    propNum = 42;

    log() {
        console.log(this.propStr);
        console.log(this.propNum);
    }
}

class Child extends Parent {
    propStr = "Hi"; // overridden
    propNum = 1337; // overridden
}

const c = new Child("Foobar");
c.log()

如果您希望初始化依赖于其他地方选择的内容,包括子类,请将它们作为参数。你仍然可以给他们合理的默认值:

class Parent {
    constructor(propStr = "Hello", propNum = 42, propShared) {
        this.propStr = propStr;
        this.propNum = propNum;
        this.propShared = propShared;
    }
    log() {
        console.log(this.propStr);
        console.log(this.propNum);
        console.log(this.propShared);
    }   
}

class Child extends Parent {
    constructor(propShared) {
        super("Hi", 1337, propShared);
    }
}

const c = new Child("Foobar");
c.log();