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;
}
From what I see in your code you don’t really need multiple inheritance. You are simply trying to mix in code from different constructors into one. This is possible and is actually really simple to achieve in JavaScript.
First let’s rewrite your code for
Player:That’s it. Simple right? Let me explain how the
applyfunction works:this.thisusually points to the global object (e.g.window).newJavaScript creates an instance of that function andthispoints to that instance.callandapplywhich are methods of every function and allow you to call that function with any value for thethispointer.So essentially when I call
WorldSpace.applywiththisas the first argument, thethispointer in theWorldSpacefunction points thethisinPlayer. You are essentially using theWorldSpaceandActiveconstructors as mixins.If you want to know more about how inheritance works in JavaScript I suggest you read this answer. Have you considered using a framework to make your life simpler?