René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Copying Objects in JavaScript

In JavaScript, when an object variable is assigned to another, it is assigend by reference. That means, both variables point to the same object. This has the implication that if a one variable's property is changed, it is changed in the other variable as well.
This might be desirable or not. If it is not, one must copy the variable. The following code fragment show a possible way to do so.
Note, this does not handle arrays of function objects.
<html>
<head><title>Copying objects with JavaScript</title>

<script language='javascript'>
  function copy_obj(o) {
    var c = new Object();

    for (var e in o) {
      c[e] = o[e];
    }
    return c;
  }

</script>

</head>
<body>

<script language='javascript'>

  var a = {num:1, txt:'one'};

  b=a;
  c=copy_obj(a);

  a.num=2;
  a.txt = 'two';

  document.writeln("<table><tr><td>&nbsp;</td><td>a</td><td>b</td><td>c</td></tr>");

  document.writeln("<tr><td>num</td>");
  document.writeln("<td>" + a.num + "</td>");
  document.writeln("<td>" + b.num + "</td>");
  document.writeln("<td>" + c.num + "</td>");

  document.writeln("<tr><td>txt</td>");
  document.writeln("<td>" + a.txt + "</td>");
  document.writeln("<td>" + b.txt + "</td>");
  document.writeln("<td>" + c.txt + "</td>");

  document.writeln("</tr></table>");

</script>

</body>
</html>