Last Updated: February 25, 2016
·
1.358K
· meddle0x53

Inheritance in JavaScript – A Cool Way

First of all we will define a helper method used to copy the properties from one object to another, overriding the common ones:

function ex (destination, source) {
  var p;

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

Let’s define our main extending method:

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;
}

The idea is that this method is called on the class to become parent class.
It has two parameters – data and staticData.
The data parameter is used to pass instance fields and methods to the child class that may override parent ones.
The staticData is used to define class level fields and methods to the child class.

Let’s use it!

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());// 2+7

Now is time for the inheritance!

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()); // 3+1=4, 3+1+9=13

Try it here

2 Responses
Add your response

over 1 year ago ·

Seems too complex to me :)

over 1 year ago ·