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 supported by TestComplete.
little example:
var p={ // simple object pName:"myName", pSex:"Male", pToStr: function(){ return (this.pName+" : "+pSex);} } var tmp={}; clone(p, tmp); p.Name="yourName"; if(p.Name==tmp.Name) // should be different Print(Error); else Print("was cloned");
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.
I used the 'polyfill' code from the Mozilla documentation for the create method:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create