2013-01-11 25 views
6

में उपयोग की जाने वाली जावास्क्रिप्ट जेनेरिक क्लोन() विधि मैं एक सामान्य क्लोन फ़ंक्शन लिखने की कोशिश कर रहा था जो सच गहरे क्लोनिंग करने में सक्षम होना चाहिए। मैं इस लिंक पर आया हूं, How to Deep clone in javascript और वहां से समारोह लिया।जीडब्ल्यूटी अनुप्रयोग

जब मैं प्रत्यक्ष जावास्क्रिप्ट का उपयोग करने का प्रयास करता हूं तो वह कोड बहुत अच्छी तरह से काम करता है। मैंने कोड में मामूली संशोधन किए और जीडब्ल्यूटी में जेएसएनआई कोड डालने की कोशिश की।

क्लोन समारोह:

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") लाइन।

कृपया मदद करें।

पीएस: मैं यहां एक सामान्य क्लोन विधि प्राप्त करने की कोशिश कर रहा हूं जिसका उपयोग किसी ऑब्जेक्ट को क्लोन करने के लिए किया जा सकता है।

+1

संभव डुप्लिकेट http://stackoverflow.com/questions/14258486 के साथ भाग मिल सकता है/गहरे क्लोन-इन-gwt) –

उत्तर

0

जीडब्ल्यूटी प्रोटोटाइप ऑब्जेक्ट्स के लिए प्रत्येक विधि नहीं है; वे मानक जावास्क्रिप्ट ऑब्जेक्ट प्रोटोटाइप का वारिस नहीं करते हैं, क्योंकि उन्हें जावा ऑब्जेक्ट्स की तरह कार्य करना होता है, जावास्क्रिप्ट ऑब्जेक्ट्स नहीं।

आप शायद Object.prototype.forEach.call (आइटम, समारोह() {})

[GWT में दीप क्लोन] (की