解决具体问题
您可以使用类型断言告诉编译器您更清楚:
public clone(): any {
var cloneObj = new (this.constructor() as any);
for (var attribut in this) {
if (typeof this[attribut] === "object") {
cloneObj[attribut] = this[attribut].clone();
} else {
cloneObj[attribut] = this[attribut];
}
}
return cloneObj;
}
克隆
截至2022年,提议允许structuredClone
深度复制多种类型。
const copy = structuredClone(value)
在使用此功能时,有一些限制。
请记住,有时编写自己的映射比完全动态地生成更好。但是,您可以使用一些“克隆”技巧来获得不同的效果。
我将在所有后续示例中使用以下代码:
class Example {
constructor(public type: string) {
}
}
class Customer {
constructor(public name: string, public example: Example) {
}
greet() {
return 'Hello ' + this.name;
}
}
var customer = new Customer('David', new Example('DavidType'));
选项1:扩散
属性:是
方法:否
深度复制:否
var clone = { ...customer };
alert(clone.name + ' ' + clone.example.type);
clone.name = 'Steve';
clone.example.type = 'SteveType';
alert(customer.name + ' ' + customer.example.type);
选项2: Object.assign
属性:是的
方法:否
深拷贝:否
var clone = Object.assign({}, customer);
alert(clone.name + ' ' + clone.example.type);
alert(clone.greet());
clone.name = 'Steve';
clone.example.type = 'SteveType';
alert(customer.name + ' ' + customer.example.type);
选项3:Object.create
属性:继承
方法:继承
深拷贝:浅继承(深层更改会影响原始对象和克隆对象)
var clone = Object.create(customer);
alert(clone.name + ' ' + clone.example.type);
alert(clone.greet());
customer.name = 'Misha';
customer.example = new Example("MishaType");
alert(clone.name + ' ' + clone.example.type);
clone.name = 'Steve';
clone.example.type = 'SteveType';
alert(customer.name + ' ' + customer.example.type);
选项4:深拷贝函数
属性: 有
方法:没有
深拷贝: 有
function deepCopy(obj) {
var copy;
if (null == obj || "object" != typeof obj) return obj;
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = deepCopy(obj[i]);
}
return copy;
}
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = deepCopy(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
var clone = deepCopy(customer) as Customer;
alert(clone.name + ' ' + clone.example.type);
clone.name = 'Steve';
clone.example.type = 'SteveType';
alert(customer.name + ' ' + customer.example.type);
cloned instanceof MyClass === true
? - Szczepan Hołyszewski