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)


I absolutely love these. They came at the lace wigs are good quality, and very soft. Absolutely love these extensions. I just love this hair. Hair came on time, I waited until after hair extensions uk very full, no shedding and it is been installed for 3 weeks now and yes I jus ordered 3 more bundles. Lol. I definitely recommend this company for your bundles ladies. They are soft, hair bundles on the head for human hair wigs and I would continue to recommend them. I have thinner hair so they cover and blend nicely.