Last Updated: February 25, 2016
·
1.334K
· padawin

Javascript inheritance

How to implement a basic inheritance system in Javascript. Or some kind of POF I did for fun...

First, an "extends" method has to be created. If a class calls it, it will inherit the properties and methods of the class given in arguments:

Object.prototype.extends = function(parent)
{
    for (var i in parent) {
        this[i] = parent[i];
    }
};

However, this method will only give access to the static methods and properties of the parent class (methods and properties of the class).

To give access to the methods and properties of the instances, this code has to be added:

childClass.prototype = new parentClass();

Final result

Object.prototype.extends = function(parent)
{
    for (var i in parent) {
        this[i] = parent[i];
    }
};

//mother class definition
function parentClass()
{
    this.foo = 'bar';
}
//a static method
parentClass.staticMethod = function()
{
    console.log('I am static');
};

//a member method
parentClass.prototype.instanceMethod = function()
{
    console.log('I am called from a parentClass instance');
};


//child class definition
function childClass()
{
    parentClass();
}

//inheritance
childClass.extends(parentClass);
childClass.prototype = new parentClass();

//method overload
childClass.prototype.instanceMethod = function()
{
    parentClass.prototype.instanceMethod();
    console.log('I am called from a childClass instance');
};

//test
var c = new childClass();
console.log('call of instanceMethod');
c.instanceMethod();
console.log('call of staticMethod');
childClass.staticMethod();
console.log('use of some property of the parent class');
console.log(c.foo);

This code will output:

call of instanceMethod
I am called from a parentClass instance
I am called from a childClass instance
call of staticMethod
I am static
use of some property of the parent class
bar

2 Responses
Add your response

Here's a better one (lovingly stolen from the chosen-jQuery plugin):

var __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { 
           for (var key in parent) { 
                if ( __hasProp.call(parent, key) ) 
                    child[key] = parent[key]; 
            } 

            function ctor() { 
                this.constructor = child; 
            } 

            ctor.prototype = parent.prototype; 
            child.prototype = new ctor();

            child.__super__ = parent.prototype; 

            return child; 
        };
over 1 year ago ·

I think with this example you can create hierarchies easier.
jsfiddle

function ex (destination, source) {
  var p;

  for (p in source) {
    if (source.hasOwnProperty(p)) {
      destination[p] = source[p];
    }
  }
  return destination;
}

function extend (data, staticData) {
  var parent = this,
      child = function () {
        if (data.initialize) {
          data.initialize.apply(this, arguments);
        } else {
          parent.apply(this, arguments);
        }
      };

  ex(child, parent);

  if (staticData) {
    ex(child, staticData);
  }
  if (!data) {
    data = {};
  }

  child.prototype = ex(Object.create(parent.prototype), data);
  child.prototype.constructor = child;
  child.prototype.__super = parent.prototype;

  return child;
}

function Foo (a, b) {
  this.a = a;
  this.b = b;
}

Foo.prototype.c = function () {
  return this.a + this.b
};

var foo = new Foo(2, 5);
console.log(foo.c());

Foo.extend = extend;

Bar = Foo.extend({
  initialize: function (a, b, d) {
    this.__super.constructor(a, b);
    this.d = d;
  },    
  d: 8,
  e: function () {
    return this.a + this.b + this.d;
  }
});

var bar = new Bar(3, 1, 9);

console.log(bar.c(), bar.e());

var Baz = Bar.extend({
  initialize: function (a, b, d, f) {
    this.__super.constructor(a, b, d);
    this.f = f;
  },
  f: 2,
  g: function () {
    return this.a + this.b + this.d + this.f;
  }
});

var baz = new Baz(3, 1, 4, 6);

console.log(baz.c(), baz.e(), baz.g());
over 1 year ago ·