Forum Discussion

APX's avatar
APX
Occasional Contributor
10 years ago

How can I clone objects in TestComplete javascript?

Hi,   a simple Question: how can I clone objects, in javascript without reference,  in TestComplete(is it possible)? I don't found a methode on MSDN and the standard methode "clone()" is not suppor...
  • APX's avatar
    10 years ago

    So here is my solution for this Problem. We do not have the the option for using 'prototype' or 'constructor'. I have my doubts in terms of this kind of solution but it's better then nothing:

     

     

    function clone( other, obj)
    {
        if ( (other === null) || (typeof other !== "object") )
        {
         obj=other;
         return true;
        }    
        obj = obj || {};
        for ( Key in other )
        {
          if(other.hasOwnProperty(Key))
          {                        
            if(typeof other[Key] == 'function') 
            {
               obj[Key]={};  
               eval("obj."+Key.toString()+"="+other[Key].toString());           
            }
            else if(typeof other[Key] == 'object') 
            {
              obj[Key]={};//
              clone(other[Key], obj[Key]);          
            }
            else
            {         
              obj[Key]=other[Key];
            }
          }
        }
        if(obj != null)return true;
        return false;
    }

     

    Usage:

    var person={
        fName: "Max",
        lName: "Mustermann",
        hight: 181,    
        motto:{
          autor:"mySelf", 
          text:"my motto",
          printMotto: function(){
            return (this.autor+" : "+this.text);
          }
        },
        printData:function(){
          return this.fName+" ->"+this.lName+" -> "+this.hight+"->"+motto.printMotto(); 
        }
      };
    
    var copy={};
    if(clone(person, copy))
       Log.Message(person.printData()+" :: "+copy.printData());
    person=null; // or you can use undefined to clear var
    Log.Message(copy.printData());
    Log.Message(person.printData());// here we will get an error
    
    
    

    I can't compare the memory address of this both variables, so it's not really 100% a deep copy 

    If you have a better way to solve that problem, post it here.

    Thanks.