Inheritance by copying properties

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.

Tags: , ,

2 Responses to “Inheritance by copying properties”

  1. JSPatterns.com » Blog Archive » Mixins Says:

    [...] Exploring common JavaScript patterns and anti-patterns   « Inheritance by copying properties [...]

  2. fashion Says:

    A formidable share, I simply given this onto a colleague who was doing a bit analysis on this. And he in fact bought me breakfast because I discovered it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love studying more on this topic. If possible, as you grow to be experience, would you thoughts updating your weblog with more details? It’s highly helpful for me. Massive thumb up for this weblog publish!

Leave a Reply