首页 > 解决方案 > Value not yet initialized in parent class when calling method from base class

问题描述

We have the following structure

abstract class testParent{
    constructor(){
        console.log(this.doSomething());
    }

    abstract doSomething():string;
}

class testChild extends testParent{
    private x:string = 'someValue';

    constructor(){
        super();
    }

    doSomething():string{
        return this.x;
    }
}

const y = new testChild();

And we noticed that the string x is not yet initialized so it returns undefined. But we would like to have this structure. What are some ways to deal with this problem?

We thought of one solution

abstract class testParent{
    constructor(){
        this.initialize();
        console.log(this.doSomething());
    }

    abstract initialize():void;

    abstract doSomething():string;
}

class testChild extends testParent{
    private x:string = '';

    initialize():void{
        this.x = 'someValue';
    }

    doSomething():string{
        return this.x;
    }
}


const y = new testChild();

But this feels quite hacky.

标签: typescriptclass

解决方案


The problem is that you're trying to access x before it is initialized. Even though you're probably not aware, in reality your constructor does this:

constructor() {
        super();
        this.x = 'someValue';
    }

which means doSomething() is called with this.x not yet being assigned a value.

Same thing happens if you omit the constructor entirely

constructor() {
        super(...arguments);
        this.x = '';
    }

You can check that this is happening if you for example debug this on the playground:

Playground

You'll have to additionally open the console (F12) to enable the breakpoint being hit

I think the most accurate solution is the one you already presented, basically your parent needs to initialise the property before calling super()


推荐阅读