Passing Objects to Functions By Value

By Rob Gravelle

As mentioned in my Passing JavaScript Function Parameters By Reference article, objects are passed to functions by reference in JavaScript. In other words, the function receives a pointer that references the original object. The benefit to this approach is that it saves memory and processing resources. Unfortunately, it can lead to trouble if the function alters the object in a way that you did not anticipate or desire. While you can't just flip a switch to pass objects by value, there are ways to produce a copy. That's precisely what we'll be learning how to do today.

Copying Arrays

Some objects, such as Arrays, are surprisingly easy to copy because they possess a couple of methods that return a copy of the array. Here's some code that utilizes the slice() method:

function modifyArray(a) {
  a[1] = 99;
  console.log(a); //prints '1, 99, 3'
}

var myArray = [1, 2, 3];
modifyArray(myArray);
console.log(a); //prints '1, 99, 3'

var myArray2 = [1, 2, 3];
modifyArray(myArray2.slice(0));
console.log(a); //prints '1, 2, 3'

The slice() method usually returns part of an array, except that we specified from element zero to the end - in other words, the whole array. Just keep in mind that the slice() method only works on arrays containing simple data types. Elements that contain objects or other arrays will be accessed by reference, thus retaining a connection with the source array. In those instances, you would need to copy the array as a full-fledged object (see below):

Copying Dates

Dates are even easier to copy because one of the constructors accepts the number of milliseconds since January 1st, 1970 - the Unix epoch.

function copyDate(aDate) {
  return new Date(aDate);
}

function compareGlobalVariableToLocal( dt1Name, dt2 ) {
  return (window[dt1Name] === dt2);
}

var myDate = new Date(2012, 0, 12); //January 12, 2012
var dateCopy = copyDate(myDate);

alert(compareGlobalVariableToLocal('myDate', myDate));   //displays true
alert(compareGlobalVariableToLocal('myDate', dateCopy)); //displays false

Cloning an Object

Most objects don't possess a native method that returns a copy of the object, so we have to do the copying ourselves. When doing so, there are two ways you can go about it. The first is to perform a shallow copy; the other is to do what's called a deep copy. In the former, all "public" method attributes and methods are copied to the new object, following the rules of assignment. Hence, primitive attributes are copied by value, while object types are assigned by reference so the both the original and copied object still point to the same object in memory. It's more efficient to perform a shallow copy, but it's not a true copy. To do that, you have to recursively copy each object property in turn. That can take a lot more resources, but sometimes it's your best option. Here's a prototype method that does the work on the this pointer. It can do both a shallow and deep copy:

Object.prototype.clone = function(deep) {
  var newObj;
  
  if (this instanceof Date) {
    newObj = new Date(this);
  }
  else if (!deep && this instanceof Array) {
     newObj = this.slice(0);
  }
  else {
    for (i in this) {
      if (i == 'clone') continue;
      if (deep && typeof this[i] == "object") {
        newObj[i] = this[i].clone();
      } else {
        newObj[i] = this[i];
      }
    } 
  }
  return newObj;
};
//call as follows
//var myObj = {attr1: 'an attribute', attr2: 42 }
//myObj.clone();

Note that the above function does not address the IE 8 DontEnum bug. For a workaround, see my Create an Object-oriented JavaScript Class Constructor article.

Using jQuery

jQuery has a convenient method that can be used to produce a copy of an object called jQuery.extend(). Just add this line to the top of your function when you don't want to modify the original:

var newObj = jQuery.extend({}, oldObj);  //performs a shallow copy

newObj = jQuery.extend(true, {}, oldObj);  //performs a deep copy

That'll copy the object for you.

Conclusion

Today we saw how to copy various JS objects both when calling a function and within the function body. JavaScript provides functions that either produce a copy or alter the original object, depending on the context. Your functions' behavior should be modeled accordingly.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •