I am developing a browser based game on a node.js server. I'm trying to implement a component based inheritance structure but I am unsure of the concepts with regards to javascript inheritance.
As far as I can make out, if I want to inherit from two component objects e.g. function Moves(){}
and function IsVisible(){}
, the usual prototypal inheritance doesn't work:
gameObject.prototype = new Moves;
gameObject.prototype = new IsVisible;
The is IsVisible
object overwrites the Moves
object as the gameObject
prototype.
Below is my attempt at creating an inherit function that takes a target object and an arbitrary number of component objects as arguments. The target object then inherits the behavior and variables from the these components.
I'm not familiar with javascript inheritance and would like to know if the below method a good way of implementing a multiple inheritance type structure in javascript?
Are there any other well established practices dealing with this problem? (If it is a problem...)
Any help would be much appreciated.
function inherit(o){
var proto = o;
for(var i = 1; i < arguments.length; i++){
var component = new arguments[i]();
for(var x in component){
proto[x] = component[x];
}
}
}
function Player(name){
var o = {};
o.name = name;
inherit(o, WorldSpace, Active);
return o;
}
function WorldSpace(){
this.pos = {x:0, y:0};
this.orientation=0;
}
function Active(){
this.acceleration = 1;
this.velocity = {x:0,y:0};
this.rotation = 0;
this.rotationSpeed = (Math.PI*2)/30;
this.throttle = false;
this.currentSpeed = 0;
this.maxSpeed = 10;
}