Stavo cercando di scrivere una funzione clona generica che dovrebbe essere in grado di eseguire la vera clonazione profonda. Ho trovato questo link, How to Deep clone in javascript e ho preso la funzione da lì.Javascript clone() metodo utilizzato nell'applicazione GWT
Questo codice funziona molto bene quando provo a utilizzare Javascript diretto. Ho apportato piccole modifiche al codice e ho provato a inserire il codice JSNI in GWT.
funzione di clone:
deepCopy = function(item)
{
if (!item) {
return item;
} // null, undefined values check
var types = [ Number, String, Boolean ], result;
// normalizing primitives if someone did new String('aaa'), or new Number('444');
types.forEach(function(type) {
if (item instanceof type) {
result = type(item);
}
});
if (typeof result == "undefined") {
alert(Object.prototype.toString.call(item));
alert(item);
alert(typeof item);
if (Object.prototype.toString.call(item) === "[object GWTJavaObject]") {
alert('1st');
result = [];
alert('2nd');
item.forEach(function(child, index, array) {//exception thrown here
alert('inside for each');
result[index] = deepCopy(child);
});
} else if (typeof item == "GWTJavaObject") {
alert('3rd');
if (item.nodeType && typeof item.cloneNode == "function") {
var result = item.cloneNode(true);
} else if (!item.prototype) {
result = {};
for (var i in item) {
result[i] = deepCopy(item[i]);
}
} else {
if (false && item.constructor) {
result = new item.constructor();
} else {
result = item;
}
}
} else {
alert('4th');
result = item;
}
}
return result;
}
E la lista sto passando a questa funzione è simile a questo:
List<Integer> list = new ArrayList<Integer>();
list.add(new Integer(100));
list.add(new Integer(200));
list.add(new Integer(300));
List<Integer> newList = (List<Integer>) new Attempt().clone(list);
Integer temp = new Integer(500);
list.add(temp);
if (newList.contains(temp))
Window.alert("fail");
else
Window.alert("success");
Ma quando eseguo questo, ottengo un'eccezione di puntatore nullo nella funzione di clone immediatamente dopo Linea alert("2nd")
.
Gentile aiuto.
P.S: Sto cercando di ottenere qui un metodo clone generico che può essere utilizzato per clonare qualsiasi oggetto.
possibile duplicato del [clone di profondo in GWT] (http://stackoverflow.com/questions/14258486/deep-clone-in-GWT) –