Javascript Proper Class constructor

后端 未结 1 2017
你的背包
你的背包 2021-01-29 04:39

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

相关标签:
1条回答
  • 2021-01-29 05:14

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题