如果您的类具有默认构造函数,则可以具有通用克隆函数:
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在类中添加一个知道如何构造和分配值的方法。
| 归档时间: |
|
| 查看次数: |
3747 次 |
| 最近记录: |