Próbowałem napisać ogólną funkcję klonowania, która powinna być w stanie wykonać prawdziwe głębokie klonowanie. Natknąłem się na ten link, How to Deep clone in javascript i wziąłem stamtąd funkcję.Javascript generic clone() metoda używana w aplikacji GWT
Ten kod działa całkiem dobrze, gdy próbuję używać bezpośredniego JavaScript. Wprowadziłem drobne modyfikacje kodu i próbowałem wstawić kod JSNI w GWT.
klon funkcja:
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;
}
A lista m przechodzącą tej funkcji jest tak:
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");
Ale kiedy wykonać to otrzymuję wyjątku null pointer w funkcji clone natychmiast po Linia alert("2nd")
.
Uprzejmy pomoc.
P.S: Próbuję uzyskać tutaj ogólną metodę klonowania, która może być używana do klonowania dowolnego obiektu.
możliwe duplikat [Głębokie klonem w GWT] (http://stackoverflow.com/questions/14258486/deep-clone-in-gwt) –