在打字稿中通过 this 从派生类型调用构造函数

2024-05-12

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

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

现在,我要创建一个新对象

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

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

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

那么我怎样才能调用构造函数Child在它的基类中?

也尝试过this https://stackoverflow.com/questions/34471231/create-new-instance-of-child-class-from-base-class-in-typescript


您可以使用 new 运算符调用构造函数,这似乎可行。我也会用this返回类型,以便克隆方法将返回派生类型而不是基类型

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);
    }   
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在打字稿中通过 this 从派生类型调用构造函数 的相关文章

随机推荐