Simple Inheritance on Javascript Objects

by dom111 on January 20th, 2009

I’ve been playing a lot with javascript lately and needed to extend an object, retaining all the existing methods but also adding more.

This simple script allows exactly that:

Object.prototype.implement = Function.prototype.implement = function(props) {
  for (var key in props) {
    this[key] = props[key];
  }
 
  return true;
}
 
Object.prototype.extend = Function.prototype.extend = function(props) {
  var obj = new this.constructor();
  obj.prototype = this.prototype;
  obj.implement(this);
 
  if (props) {
    obj.implement(props);
  }
 
  return obj;
}

It should be used similar to how you would extend a class in PHP i guess:

var Class = function() {
}
 
Class.prototype.test = function() {
  alert('test');
}
 
var Class2 = Class.extend();
 
Class2.prototype.test2 = function() {
  alert('test2');
}
 
var obj = new Class();
 
var obj2 = new Class2();
 
obj.test();
// alerts test
obj.test2();
// throws an exception
obj2.test();
// alerts test
obj2.test2();
// alerts test2

I know there are many frameworks that probably already do this better, but if you just need a simple object extension method, this should work.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS