GWT应用程序中使用的Javascript泛型clone()方法

LPD*_*LPD 6 javascript gwt jsni gwt-2.5

我试图编写一个通用克隆函数,它应该能够进行真正的深度克隆.我遇到过这个链接,如何深入克隆javascript并从那里获取功能.

当我尝试使用直接Javascript时,该代码工作得很好.我在代码中做了一些小修改,并尝试在GWT中输入JSNI代码.

克隆功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

传递给这个函数的列表是这样的:

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" );
Run Code Online (Sandbox Code Playgroud)

但是当我执行此操作时,我会立即在克隆函数中获得空指针异常alert("2nd").

请帮助.

PS:我试图在这里获得一个可用于克隆任何对象的通用克隆方法.

Aja*_*jax 0

GWT 原型对象没有 forEach 方法;它们不继承标准的 javascript 对象原型,因为它们的行为应该像 java 对象,而不是 javascript 对象。

您可能可以摆脱 Object.prototype.forEach.call(item, function(){})