My situation is that I am working on a Canvas game using Box2DWeb, so I have a class called Sprite that draws an image to the Canvas, I now want to create a PhysicsSprite class that inherits methods and properties from Sprite.
My Sprite class (Sprite.js):
Sprite = function (position, dimension, image) {
this.Position = position;
this.Dimension = dimension;
if (image)
this.Image = image;
...
this.Draw = function (g) {
...
}
...
};
And I am setting the prototype in PhysicsSprite (PhysicsSprite.js) like so:
PhysicsSprite = function(position, dimension, world) {
this.prototype = new Sprite(position, dimension, undefined);
//alert(this.prototype.Position.X)
var body = CreateBody();
this.GetBody = function () { return body; }
this.Draw = function (g) {
...
}
function CreateBody () {
...
}
};
Note the alert(this.prototype.Position.X), which does alert me of the position, but if I change the code to this.Position.X, I get an error, and similarly, if I have an instance of PhysicsSprite, I have to explicitly call the prototype.
This lead me to think that I haven’t set the Object’s prototype, merely created a property called prototype, and set that to a new Sprite.
If someone could help me, and explain what I am doing wrong, that would be much appreciated.
I am dyslexic, so I always misspell variables, which is frustrating, so that was the first thing I looked for, but everything looks fine to me.
That’s right. Also, you are not making use of the function’s prototype at all, since you assign each function directly to the instance (
this.Draw = function() ...) instead of the prototype.In JavaScript you have something called constructor functions. Every function called with the
newoperator is a constructor function.When a function is called that way (
new SomeFunc()), a new object is created (lets call it an isntance) which inherits from the object referenced bySomeFunc.prototypeand this instance is available inside that function viathis.Now, inheritance basically comes down to having a prototype (
SomeFunc.prototype) which instead of being an (nearly) empty object (the default), inherits from another function’s prototype.Example:
This is how
inheritscould look like (this implementation is used by the Google Closure library):You see that
Child.prototyperefers to an instance ofTmp. ButTmp‘s prototype is the same asParent‘s prototype. That means, the instance returned bynew Tmp()inherits fromParent‘s prototype, and since this instance is the prototype ofChild, all instances ofChildwill inherit fromParent.prototypeas well.With ECMAScript 5, this can be simplified to
but it’s essentially the same. It creates a new object which inherits from
Parent.prototype.Further reading:
newthis.call()