GWT应用程序中使用的Javascript通用克隆()方法
我试图编写一个通用的克隆函数,它应该能够进行真正的深度克隆。我遇到了这个链接,并从那里获取了函数 当我尝试使用DirectJavaScript时,该代码工作得非常好。我对代码做了一些小的修改,并尝试将JSNI代码放入GWT中 克隆功能:GWT应用程序中使用的Javascript通用克隆()方法,javascript,gwt,jsni,gwt-2.5,Javascript,Gwt,Jsni,Gwt 2.5,我试图编写一个通用的克隆函数,它应该能够进行真正的深度克隆。我遇到了这个链接,并从那里获取了函数 当我尝试使用DirectJavaScript时,该代码工作得非常好。我对代码做了一些小的修改,并尝试将JSNI代码放入GWT中 克隆功能: deepCopy = function(item) { if (!item) { return item; } // null, undefined values check var types = [ Number,
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" );
List List=new ArrayList();
添加(新整数(100));
添加(新整数(200));
添加(新整数(300));
List newList=(List)新尝试().clone(List);
整数温度=新整数(500);
列表。添加(临时);
if(newList.contains(temp))
窗口警报(“失败”);
其他的
窗口警报(“成功”);
但当我执行此操作时,克隆函数中的空指针异常会立即出现在警报(“第二”)
行之后
请帮忙
附言:我试图在这里得到一个通用的克隆方法,可以用来克隆任何对象。GWT原型对象没有forEach方法;它们不会继承标准的javascript对象原型,因为它们的行为应该类似于java对象,而不是javascript对象 您可能会忽略Object.prototype.forEach.call(item,function(){})的可能重复项