javascript, object orientation, inheritance Part 2

This entry was posted by on Tuesday, 21 June, 2011 at

First the base Object

Javascript has a rather unusual aproach to inheritance. It relies on prototypes. Each object has a prototype that defines it’s blueprint – very much like a class. Lets start with the parent object

  function Parent() {
    this.someVal = ‘some value of the parent’;
    this.getVal = function () {
      return this.someVal;

    this.doStuff = function () {
      return ‘runnig Parent.doStuff()’;

Now create a Child object that inherits

So far for the basics. Lets add a child to this Parent

  function Child() {
    this.someVal = ‘some value of the child’;
    this.getParentVal = function() {
      return Child.prototype.someVal;
    this.doChildishStuff = function() {
      return this.doStuff() + ‘ plus doing my own stuff’;
  Child.prototype = new Parent();

Child.prototype = new Parent();  tells the child Class that it should go look into the Parent class if you call some function on it that it does not have itself. If Parent does not have it, maybe there is a .prototype of Gradparent that has it.

Now lets try it out

  var par = new Parent();
  alert(‘par.someVar: ‘ + par.someVal);
  alert(‘par.getVal(): ‘ + par.getVal() );
  alert(‘par.doStuff(): ‘ + par.doStuff() )

  var kid = new Child();
  alert(‘kid.someVal: ‘ + kid.someVal);
  alert(‘kid.doStuff(): ‘ + kid.doStuff())
  alert(‘kid.doChildishStuff(): ‘ + kid.doChildishStuff())
  alert(‘kid.getParentVal(): ‘ + kid.getParentVal())

Works neatly. You can go along and access the prototypes properties if you need it, you simply overwrite a method that does not behave like you would like it. This should help you if you need to do inheritance in Javascript.

There is another way to reuse code: parasitic inheritance

But you can do other tricks to avoid doublicate coding. There is a trick i like to call parasitic inheritance. As functions are variables and accessable you can borrow them from other objects. Without the hassle of inheritance you can reuse code. Let’s see

  function Other () {}
  Other.prototype.someFunction = function() {
    return ‘parasiticFunction original from Unrelated’;

  Child.prototype.doTrick = Other.prototype.someFunction;
  alert(‘Kid does a neat trick :’ + kid.doTrick())

Other is a different Object with a method someFunction. By assigning Child.prototype.doTrick to that variable you get the function.

Changing just one Instance of a running Object

But maybe you do not want to change the behaviour of all Child objects, just that of one instance. Well, there is a way to do that

  function onTheFly() {
    return ‘adding functions to an instance at runtime ‘;
  kid.otherTrick = onTheFly;

  alert(‘kid got a new trick: ‘ + kid.otherTrick() );

Instead of messing with Child.prototype that changes all running Childs you can just create a new variable in kid (or overwrite another) with a new function

Leave a Reply