克隆JavaScript对象的最有效方法是什么?我已经看到obj = eval(uneval(o));
被使用,但这是非标准的,只有Firefox支持.
我做过类似的事情,obj = JSON.parse(JSON.stringify(o));
但质疑效率.
我也看到了具有各种缺陷的递归复制功能.
我很惊讶没有规范的解决方案.
我有一个超类是父(Entity
)对于很多子类(Customer
,Product
,ProductCategory
...)
我正在寻找动态克隆在Typescript中包含不同子对象的对象.
例如:a Customer
有不同的Product
人有ProductCategory
var cust:Customer = new Customer ();
cust.name = "someName";
cust.products.push(new Product(someId1));
cust.products.push(new Product(someId2));
Run Code Online (Sandbox Code Playgroud)
为了克隆整个对象树,我创建了一个函数 Entity
public clone():any {
var cloneObj = new this.constructor();
for (var attribut in this) {
if(typeof this[attribut] === "object"){
cloneObj[attribut] = this.clone();
} else {
cloneObj[attribut] = this[attribut];
}
}
return cloneObj;
}
Run Code Online (Sandbox Code Playgroud)
在new
上升时,它被transpiled为JavaScript以下错误:error TS2351: Cannot use 'new' with an expression whose type lacks a call or …
如何在Angular中复制对象并丢失其引用?
使用AngularJS,我可以使用angular.copy(object)
,但是我在Angular中使用它时遇到了一些错误.
EXCEPTION:ReferenceError:
angular
未定义