Javascript object - pass by value and not by reference

Discussion in 'JavaScript' started by knapsack3, Oct 12, 2007.

  1. #1
    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.
     
    knapsack3, Oct 12, 2007 IP
  2. Jamie18

    Jamie18 Peon

    Messages:
    201
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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..
     
    Jamie18, Oct 12, 2007 IP
  3. knapsack3

    knapsack3 Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi

    Thanks. It still doesn't seem to work. Can you please share an example.
     
    knapsack3, Oct 12, 2007 IP
  4. knapsack3

    knapsack3 Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Hi, the problem is I don't know how to do it. It would be helpful to have an example.
     
    knapsack3, Oct 12, 2007 IP
  5. knapsack3

    knapsack3 Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    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.
     
    knapsack3, Oct 12, 2007 IP