I am trying to create a class that in its constructor uses some helper functions. Is there a way to move these helpers to the prototype? The problem is that the constructor does
I want to move stuff to the prototype, because if I understood correctly, these functions are not tied to a single object, so if I have multiple objects they will still call the same code but with different context.
Yes. However, that is not what you want: The asynchronous callbacks need to be tied on specific instances.
If you don't want to have too much stuff floating around your constructor, you might reconsider your design:
function Class(model) {
this.id = model._id;
this.core = model;
}
Class.prototype.addPlayer = function(player, callback) {
gameOps.addPlayer(player, this.model, callback);
};
Class.fromDatabase = function(id, callback) {
function addCore(err, model) {
if (err)
callback(err);
else
callback(null, new Class(model))
}
function addTopology() {
}
if (arguments.length === 2) {
gameOps.findById(id, addCore)
} else {
callback = id
gameOps.create(addCore)
}
}