Hi I have 3 javascript files: Game.js, Player.js, Drawable.js.
Now in Game.js I want to create an object _player, that is Drawable and than that is Player. This means that _player is a Player Object, that is a class that EXTENDS Drawable.
Drawable.js
function Drawable(x, y, src)
{
this.x = x;
this.y = y;
this.img = new Image();
this.img.src = src;
this.width = this.img.width;
this.height = this.img.height;
this.draw = function(canvas)
{
canvas.drawImage(this.img,this.x, this.y);
}
this.midpoint = function()
{
return {
x: this.x + this.width/2,
y: this.y + this.height/2};
}
}
}
Player.js
function Player()
{
this.moveLeft = function()
{
this.x -= 3;
}
this.moveRight = function()
{
this.x += 3;
}
this.moveUp = function()
{
this.y -= 3;
}
this.moveDown = function()
{
this.y += 3;
}
}
Game.js
var _player;
_player = new Player();
_player.draw(...);
_player.moveLeft();
...
...
This is what I want to do. I’ve tried to put Player.prototype = new Drawable; but It doesn’t work. How can I do?
If you want player objects to behave such that you can call
then the
drawandmoveLeftfunctions need to be stored as properties in every player object (yikes) or somewhere on a player object’s prototype chain.Which brings up one comment on your actual code: those functions should be in prototypes, not the actual objects.
So, to answer your actual problem…
The first thing you should do is place the methods in prototypes.
Then you need to make the prototype of a player’s prototype be the prototype for all drawables.
That may sound confusing, but here is the money line:
Do this before creating players with
new Player. 🙂ADDENDUM
Live Demo — which also shows you how to do the “constructor” thing so you can build a player with an initial x and y.