1. Computing

JavaScript By Example

Object Oriented: 17. Object Copy

By

When you use an assignment statement to copy an object, JavaScript does a copy by reference.This basically means that the new variable you are assigning the object to is not a completely new and separate object but is simply an alias for the current object. Where you do this any changes made to the properties and methods via the one variable name will update the single copy of the object that both names refer to and if you reference the property or method using the other name you will be accessing that updated value.

The alternative to copy by reference is to copy by value. In terms of objects this means that we want to create an identical but completely separate object so that while both names will have the same properties and methods having the same values at the time the copy is made, any changes subsequently made to one will not affect the other.

Copying an object in order to create a brand new object is not quite as straightforward in JavaScript as creating a reference is. To make a complete copy of the object we need to create a brand new object and then copy each property and method across from the original object to the new one. Just going through all pf the properties and methods directly attached is not sufficient either. We also need to copy any sub-objects that are a part of the object as well.


deepCopy = function(p,c) {
var c = c||{};
for (var i in p) {
  if ('object' === typeof p[i]) {
    c[i] = (p[i].constructor === Array)?[]:{};
    deepCopy(p[i],c[i]);
  } else c[i] = p[i];}
return c;
}
 
child = deepCopy(parent);

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Object Oriented
  7. JavaScript By Example - Object Oriented: Object Copy

©2014 About.com. All rights reserved.