OOP Inheritance in javascript

(Depends who you ask but) Javascript doesn’t natively support inheritance. It can be implemented to support object-oriented programming and encapsulation pretty easily, but inheritance is not offered automatically.

There are many patterns on the web on how write javascript to provide inheritance. Here’s the simplest (perhaps most common (and incorrect)) one:

function Animal(numLegs) {
  console.log("Animal instantiated");
  this.numLegs = numLegs;
}
// define animal-specific variables and methods
Animal.prototype...

function Dog() {
  console.log("Dog instantiated") {
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;

// define dog-specific variables and methods
Dog.prototype...

var dog = new Dog();

While this works on very simple cases, it doesn’t work well for passing constructor params. In fact, Animal’s numLegs variable will always be undefined.

Other patterns for supporting inheritance can be found in these posts:
http://stackoverflow.com/questions/1645027/popular-javascript-inheritance-patterns
http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript#1598077

I haven’t personally tried all the above patterns, but they seem messy at best.

The best, simplest, and of course correct pattern, I’ve found is from here.

You can read the details of why it works from the blog, but here is a quick primer:

// put this helper method somewhere
function inheritPrototype(childObject, parentObject) {
  var copyOfParent = Object.create(parentObject.prototype);
  copyOfParent.constructor = childObject;
  childObject.prototype = copyOfParent;
}

function Animal(numLegs) {
  this.numLegs = numLegs;
}

function Dog(numLegs, furColor) {
  this.furColor = furColor;
  Animal.call(this, numLegs);
}

inheritPrototype(Dog, Animal);

var dog = new Dog(4, 'brown');

Simple and correct.

Advertisements
Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: