我试图编写一个通用克隆函数,它应该能够进行真正的深度克隆。我遇到过这个链接,如何在 javascript 中深度克隆 https://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript并从那里获取该功能。
当我尝试直接使用 Javascript 时,该代码运行得很好。我对代码做了一些小修改,并尝试将 JS 代码放入 GWT 中。
克隆功能:
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;
}
传递给该函数的列表如下所示:
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" );
但是当我执行这个时,我立即在克隆函数中得到空指针异常alert("2nd")
line.
请帮忙。
P.S:我试图在这里获得一个可用于克隆任何对象的通用克隆方法。