Javascript适当类构造函数 [英] Javascript Proper Class constructor

查看:113
本文介绍了Javascript适当类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个类,在其构造函数中使用一些帮助函数。有没有办法把这些助手移到原型?问题是,构造函数对数据库做一些异步调用,我需要在回调函数中的应用程序,所以我可以在数据检索后继续执行。

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 some asynchronous calls to the database and I need to apps in a callback function so I can continue execution after the data was retrieved.

我想移动东西到原型,因为如果我理解正确,这些函数不绑定到一个单一的对象,所以如果我有多个对象,他们仍然会调用相同的代码但具有不同的上下文。

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.

   Class = function(id, callback) {
    var that = this,
        addCore = function(err, model) {
            that.id = model._id
            that.core = model
            callback(err, that)
        },
        addTopology = function() {

        }

    if (arguments.length === 2) {
        gameOps.findById(id, addCore)
    } else {
        callback = id
        gameOps.create(addCore)
    }
}

Class.prototype = {
  addPlayer: function(player, callback) {
    gameOps.addPlayer(player, this.model, callback)
  }
}


推荐答案


我想将原型移动到原型,因为如果我理解正确,绑定到单个对象,所以如果我有多个对象,他们仍然会调用相同的代码,但使用不同的上下文。

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)
    }
}

这篇关于Javascript适当类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆