I'm writing a simple platform game using javascript and html5. I'm using javascript in an OO manner. To get inheritance working i'm using the following;
// http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance/
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];
}
};
For the sake of this post consider the following example;
function A() {
this.Name = 'Class A'
}
A.prototype.PrintName = function () {
alert(this.Name);
}
function B() {
this.A();
}
copyPrototype(B, A);
function C() {
this.B();
}
copyPrototype(C, B);
var instC = new C();
if (instC instanceof A)
alert ('horray!');
As I understand it I would expect to see a horray alert box, because C is an instance of C & B & A. Am I wrong? Or am I just using the wrong method to check? Or has copyPrototype knackered the instanceof operator?
Thanks as always for taking the time to read this!
Shaw.
The problem is that the
copyPrototype
function only copies the properties from a constructors prototype to another one, for example, at the end, the intenal[[Prototype]]
link ofC.prototype
simply points toObject.prototype
.The prototype chain of
instC
and constructor's prototypes look like this:The
instanceof
operator traverses the prototype chain, yourinstC
object, as you can see, will have on its prototype chain onlyC.prototype
andObject.prototype
.You can achieve what you want by setting your constructor's prototypes to be object instances of their "parent" constructors, for example:
Now the prototype chain of the
instC
object looks like this:Recommended article:
Ok I've found a solution which keeps the instanceof function working, as well as allowing me to pass constructor parameters through the inheritance chain. The solution is detailed here; https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model - my class structure now looks like this;
Thanks CMS for highlighting to me why this wasn't working!!
You can check out the full project (well an older build which, at time of writing has yet to see this new OO method put in the whole way through) up at http://8weekgame.shawson.co.uk/ - just check out my latest posts.
Recently found a nice implementation of OO javascript by John Resig (The jQuery Guy!) which I shall be using for future projects; http://ejohn.org/blog/simple-javascript-inheritance/
These days you shouldn't need .prototype = new Thing(), I think I'm late to the party but you can just use Object.create on the prototype of the parent and then override the methods you're interested in overriding. An example:
If you run this code in node you will get:
No worry about parameters to constructors or any such craziness.