Javascript Proper Class Constructor
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 so
Solution 1:
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:
functionClass(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) {
functionaddCore(err, model) {
if (err)
callback(err);
elsecallback(null, newClass(model))
}
functionaddTopology() {
}
if (arguments.length === 2) {
gameOps.findById(id, addCore)
} else {
callback = id
gameOps.create(addCore)
}
}
Post a Comment for "Javascript Proper Class Constructor"