OO & Inheritance with Javascript


I’m getting ready to start a game development project and getting my OO Javascript up to scratch- I’ve been googling around for a while as there seems to be a whole load of different ways to implement OO and in particular inheritance in javascript.  I’ve finally found a method that work’s reliably, and with multiple generation of inheritance- It’s from an article on the site point website – for quick reference I will cut to the meat and give a usage example- for details see the original article;

add this function to your project;

function copyPrototype(descendant, parent) {
  var sConstructor = parent.toString();
  var aMatch = sConstructor.match( /\s*function (.*)\(/ );
  if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; }
  for (var m in parent.prototype) {
    descendant.prototype[m] = parent.prototype[m];
  }
};

Then define your classes (prototypes) like so;

function AClass(param) {
   this.Text=param;
}
AClass.prototype.Speak = function() {
  alert(this.Text);
}

function BClass(param, name) {
  this.AClass(param);
  this.Name = name;
}
copyPrototype(BClass, AClass);
BClass.prototype.Speak = function() {
  alert('Hi ' + name);

  // Call overridden parent method...
  AClass.prototype.Speak.apply(this);
}

So the above example will give you 2 classes- B is derived from A.  Calling AClass.Speak will give you a single alert with the contents of the 'text' property, whereas BClass.Speak will give you two text boxes; the first greeting you by name, and the second being the alert box from AClass.  I've tested this myself with multiple generations of inheritance and it worked fine, where other methods have not.

  1. No comments yet.
(will not be published)