Reputation: 543
I'm trying to implement classical inheritance in Javascript using RequireJS modules to build a game engine using HTML5. I've tried using John Resig's Class.js but it doesn't seem to be work the way I expected. Here is my Github rep for the project, the app can be run w/o a server if you download the files and open index.html in the client folder.
In the app I create a base class called Entity. An entity is the base class for all objects in the game and is extended by a number of other classes. The sprite class extends the entity class and includes animation methods. The player class extends the sprite class.
The issue appeared when I created a class named Image to extend the Entity class. Both the Player and Image classes extend entity (player goes entity->sprite->player), but when Player sets a velocity it also effects instances of Images? I added a console.log that prints the objects velocity in the Image's think function (game loop tick). If you press the arrow keys to make the player walk around you will see the player's velocity coming from the Image think print.
Shouldn't they be independent objects with individual attributes? That's what I'm going for. Any ideas on what I'm doing wrong or a link/pattern to accomplish proper inheritance?
Upvotes: 1
Views: 1100
Reputation: 4755
Entity#velocity should be initialized in the constructor rather than in the "class definition" (although, there is no such thing in JavaScript, even with helper libraries such as John Resig's Class.js).
All JavaScript variables and properties are merely pointers to a different location in memory. Your code was simply changing the velocity
property's x
property, without actually changing the reference of velocity
, and hence why the change in the property x
is mirrored in other objects.
So instead of:
var Entity = Class.extend({
velocity: { x: 0, y: 0 },
init: function () { }
});
You would do:
var Entity = Class.extend({
init: function () {
this.velocity = { x: 0, y: 0 };
}
});
Upvotes: 1