我“只是”尝试在 typescript 中克隆一个实例。
jQuery.extend(true, {}, instance)
不起作用,因为没有复制方法
非常感谢任何帮助
最佳答案
如果你的类有一个默认的构造函数,你可以有一个通用的克隆函数:
function clone<T>(instance: T): T {
const copy = new (instance.constructor as { new (): T })();
Object.assign(copy, instance);
return copy;
}
例如:
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"
如果你的类更复杂(有其他类实例作为成员和/或没有默认构造函数)然后在你的类中添加一个 clone
方法,它知道如何构造和分配值.
关于typescript - 在 typescript 中克隆一个类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42736001/