Call constructor from derived type via this in typescript

眉间皱痕 提交于 2021-01-27 05:57:46

问题


In my typescript I'm trying to create/clone an child-object via a method in the base-class. This is my (simplified) setup.

abstract class BaseClass<TCompositionProps> {
    protected props: TCompositionProps;

    protected cloneProps(): TCompositionProps { return $.extend(true, {}, this.props); } // can be overwriten by childs

    constructor(props: TCompositionProps){
        this.props = props;
    }

    clone(){
        const props = this.cloneProps();
        return this.constructor(props);
    }   
}

interface IProps {
    someValues: string[];
}

class Child extends BaseClass<IProps>{
    constructor(props: IProps){
        super(props);
    }
}

Now, I'm going to create a new object

const o1 = new Child({someValues: ["This","is","a","test"]};

// get the clone
const clone = o1.clone();

The constructor is hit (but it's just the call to the function), meaning there is no new object created. When using return Child.prototype.constructor(props) instead I get my new object.

So how can I call the constructor of Child in it's base-class?

Also tried this


回答1:


You can invoke the constructor with the new operator, that seems to work. Also I would use this for the return type so that the clone method will return the derived type not the base type

abstract class BaseClass<TCompositionProps> {
    protected props: TCompositionProps;

    protected cloneProps(): TCompositionProps { return $.extend(true, {}, this.props); } 

    constructor(props: TCompositionProps){
        this.props = props;
    }

    clone() : this{
        const props = this.cloneProps();
        return new (<any>this.constructor)(props);
    }   
}


来源:https://stackoverflow.com/questions/45870365/call-constructor-from-derived-type-via-this-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!