通过打字稿中的此类型从派生类型调用构造函数 [英] Call constructor from derived type via this in typescript

查看:49
本文介绍了通过打字稿中的此类型从派生类型调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的打字稿中,我试图通过基类中的方法创建/克隆子对象.这是我的(简化)设置.

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();

构造函数被命中(但这只是对函数的调用),这意味着没有创建新对象.当使用返回Child.prototype.constructor(props)时,我得到了新对象.

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.

那么如何在其基类中调用 Child 的构造函数?

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

还尝试了

推荐答案

您可以使用new运算符调用构造函数,这似乎可行.另外,我将使用 this 作为返回类型,以便clone方法将返回派生类型而不是基本类型

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);
    }   
}

这篇关于通过打字稿中的此类型从派生类型调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆