Reputation: 205
Basically I am trying to figure out how to avoid having a lot of arguments in a constructor in javascript. The reason is that I am making a space based game with a friend for fun, and the ships are module based. At the moment they can have a engine and many sensors, weapons and colony modules. More will probably come. Each ship is built from a spec, so to make a ship you just give it a spec and the constructor of the ship handles the rest. But when making a spec I need to provide the modules. What I want to avoid is doing this:
ShipSpec = function(civ, name, hull, engine, sensors, weapons, colony, ...) {}
And I am not sure what the best solution is. At the moment I have a visitor pattern solution, where each module has a "register" method. This method has one argument and will then register itself with that argument (if the module is a weapon it calls the method for registering a weapon, if its a sensor it calls the method for registering a sensor etc). So then I can do:
ShipSpec = function(civ, name, hull, engine, modules) {}
However, I feel like it might be a bit complicated. Maybe. I have an unfortunate ability to complicate things a bit sometimes. Would it be better to create a spec and then add the modules to it after its creation? Or is this solution fine? Is there another solution to this problem?
And we plan to make so the player can create specs and maybe modify existing specs, so I want to make it easy to do so in a good way.
Take care, Kerr
Upvotes: 2
Views: 127
Reputation: 35970
Consider using an spec object as a constructor argument:
var spec = {
civ: "...",
name: "...",
hull: "...",
...
};
ShipSpec = function(spec) {}
This way:
Upvotes: 12