Posts Tagged ‘copy’

Inheritance by copying properties

Monday, September 14th, 2009

Let's take a look at an inheritance pattern – inheritance by copying properties. In this pattern an object gets functionality from another object, simply by copying it.

function extend(parent, child) {
  var i, child = child || {};
  for (i in parent) {
    child[i] = parent[i];
  }
  return child;
}

In this implementation child is optional, if you don't pass an existing object to augmented, than a brand new is created and returned.

It's a very simple implementation, just looping through the parent’s members and copy them over.

Now you may say "Hey, hey, hey, what about performance? Isn’t it inefficient to copy around properties like this?". Technically yes, but if that’s your performance bottleneck, you probably have the fastest JavaScript app ever.

This works for many applications, Firebug has an extend() methods that does this. Firebug is a pretty complex app and this works for it, so it should work for many other applications.

And one more heads-up - this is a "shallow copy" of the object, if you need you can do a "deep copy" - checking if the property you're about to copy is an object and if so, recursively iterate through the properties.