Javascript, Inheritance And Polymorphism

With my object oriented background coding in C#, I’ve been looking for a good way to do inheritance and polymorphism in Javascript that is similar to object oriented languages.   Because of my object oriented background, I’m not really fond of the prototype syntax.  My big problem was trying to find a strategy that would allow my extended class and allow me to call the “super” or “parent” methods, even in override methods.  Below is a strategy that will do just that.

Inheritance

There are a few different ways of practicing inheritance is Javascript.  The one I prefer is similar to the Parasitic Inheritance model:

function ClassA(){
  this.doSomething = function(){
    console.log("something done");
  }
}

function ClassB(){
  ClassA.call(this);
}

var classB = new ClassB();
classB.doSomething(); //something done

Polymorphism

To polymorph in Javascript class is a little more complicated.  I really needed a model that would allow me to call the parent (or super) methods if needed, just like a C# or Java.

Here’s how I did it using JQuery:

function Rectangle(){
  var width = 0;
  var height = 0;

  this.setWidth = function(newValue){
    width = newValue;
  } 

  this.setHeight = function(newValue){
    height = newValue;
  }

  this.getSize = function(){
    return { width: width, height: height };
  }
} 

function Square(){
  Rectangle.call(this);
  var parent = $.extend({}, this);

  this.setWidth = function(newValue){
    parent.setWidth(newValue);
    parent.setHeight(newValue);
  } 

  this.setHeight = function(newValue){
    parent.setWidth(newValue);
    parent.setHeight(newValue);
  }
} 

var square = new Square();
square.setWidth(10);
console.log(square.getSize()); // { width: 10, height: 10 }

This method allows us to polymorph a class and give us the ability to call “super” methods if needed.

If you don’t want to use JQuery, here’s an example of keeping references to the parent methods:

function ClassB(){
  ClassA.call(this);

  //create parent and set all method references
  var parent = {};
  var keys = Object.keys(this);
  for (var key in keys) {
    parent[keys[key]] = this[keys[key]];
  }
}

Its a bit more code, but it does the same thing.  It will allow you to call the parent methods and polymorph your extended class.

Enjoy!

Leave a comment