0

Is there a quick way to "super" deep clone a node, including its properties? (and methods, I guess)

I've got something like this:

var theSource = document.getElementById("someDiv")
theSource.dictator = "stalin";

var theClone = theSource.cloneNode(true);

alert(theClone.dictator); 

The new cloned object has no dictator property. Now, say I've got a thousand properties attached to theSource - how can I (non-explicitly) transfer/copy them to the clone?

// EDIT

@Fabrizio

Your hasOwnProperty answer doesn't work properly, so I adjusted it. This is the solution I was looking for:

temp = obj.cloneNode(true);

for(p in obj) {
  if(obj.hasOwnProperty(p)) { eval("temp."+p+"=obj."+p); }
}
4

1 回答 1

2

保存大量属性的最佳方法可能是创建一个属性对象,您可以在其中存储所有属性,例如

thesource.myproperties = {}
thesource.myproperties.dictator1 = "stalin"; 
thesource.myproperties.dictator2 = "ceasescu"; 
thesource.myproperties.dictator3 = "Berlusconi";
...

那么你只需要复制一个属性

theclone.myproperties = thesource.myproperties

否则for对您存储的所有属性进行循环

for (p in thesource) {
  if (thesource.hasOwnProperty(p)) {
    theclone.p = thesource.p;
  }
}
于 2010-11-04T08:48:19.907 回答