在打字稿中克隆类实例

Fri*_*ell 5 typescript

我只是在尝试在打字稿中克隆实例。

jQuery.extend(true, {}, instance)

不起作用,因为未复制方法

任何帮助是极大的赞赏

Nit*_*mer 9

如果您的类具有默认构造函数,则可以具有通用克隆函数:

function clone<T>(instance: T): T {
    const copy = new (instance.constructor as { new (): T })();
    Object.assign(copy, instance);
    return copy;
}
Run Code Online (Sandbox Code Playgroud)

例如:

class A {
    private _num: number;
    private _str: string;

    get num() {
        return this._num;
    }

    set num(value: number) {
        this._num = value;
    }

    get str() {
        return this._str;
    }

    set str(value: string) {
        this._str = value;
    }
}

let a = new A();
a.num = 3;
a.str = "string";

let b = clone(a);
console.log(b.num); // 3
console.log(b.str); // "string"
Run Code Online (Sandbox Code Playgroud)

操场上的代码

如果您的类更复杂(具有其他类实例作为成员和/或没有默认构造函数),则clone在类中添加一个知道如何构造和分配值的方法。