Debt Help - Free Ringtones - Debt Help - Loans - Mortgage Calculator

PDA

View Full Version : Javascript object - pass by value and not by reference


knapsack3
Oct 12th 2007, 6:37 am
Hi,

I have a javascript object. I pass it to a function where certain attributes are changed and displayed on screen. Once I am out of that function, I need to get the original object back so that I can do further processing.
I did this:
OrijObj : (Object declaration, with attirbutes and values)
copyObj = OrijObj;

Later in the code, when I try to access the 'copyObj', it is also affected, as javascript uses pass by reference.

Is there any way I can make sure the copyObj is not affected at all?

Thanks.

Jamie18
Oct 12th 2007, 6:50 am
i'm not sure but you might have to create the copyObj using new...
i.e. copyObj = new Object... and then setting the attributes to be the same..

knapsack3
Oct 12th 2007, 7:08 am
Hi

Thanks. It still doesn't seem to work. Can you please share an example.

knapsack3
Oct 12th 2007, 7:32 am
Hi, the problem is I don't know how to do it. It would be helpful to have an example.

knapsack3
Oct 12th 2007, 8:39 am
I have found a solution for this:

function clone(s) {
for(p in s)
this[p] = (typeof(s[p]) == 'object')? new clone(s[p]) : s[p];
}

cloneObj= new clone(origObj);

Once this is done, even if the origObj changes, the cloneObj remains the same.