Javascript Objects Pass by Reference

Just as you expect in your good ol’ compiled C# code (and other languages), JavaScript naturally passes its primitives by val, and its complex objects by reference. Depending on what your doing this could nuke something in your code if your not aware of it being passed this way. In some cases, passing an object by val is preferred!

In order to understand the scenario (in case your unfamiliar with it), following is an example showing a value in an object that we want to stay as “4”:

  1.  
  2.     var ob = new Object();
  3.     ob.TestVal = 4;
  4.  
  5.     alert(ob.TestVal);
  6.  
  7.     var newOb = ob;
  8.     newOb.TestVal = 3;
  9.  
  10.     alert(ob.TestVal);

Now for the solution! Here is how to overcome the scenario quite easily:

  1.  
  2.     var ob = new Object();
  3.     ob.TestVal = 4;
  4.  
  5.     alert(ob.TestVal);
  6.  
  7.     var newOb = deepCopy(ob);
  8.     newOb.TestVal = 3;
  9.  
  10.     alert(ob.TestVal);

You will notice the use of a function called “deepCopy”. This is a function you must include in your code to use as follows:

  1.  
  2. // creates a dopy copy of a javascript object
  3. function deepCopy(p, c) {
  4.     var c = c || {};
  5.     for (var i in p) {
  6.         if (typeof p[i] === ‘object’) {
  7.             c[i] = (p[i].constructor === Array) ? [] : {};
  8.             deepCopy(p[i], c[i]);
  9.         } else c[i] = p[i];
  10.     }
  11.     return c;
  12. }

And thats how you do it! For the life of me, I cannot remember where I originally grabbed this nice little function from, but please advise if you know!

Leave a Reply