javascript - 如何使用我可以推送到的方法和数组制作 Javascript 类?

标签 javascript

我想定义一个管理消息的 Javascript 对象。在这个对象中,我需要一个数组,我可以执行 push() 来:

MsgObjCollection.push(MsgObj)

本质上,我试图用一堆 MsgObjs 填充 MsgObjCollection 对象。每个 MsgObj 都有 3 个变量 messagesText、timeStamp、source(发送或接收)。

此外,我还需要一些方法,例如:

MsgObjCollection.Sent.Count       // Counts the number of sent messages
MsgObjCollection.Received.Count   // Counts the number of received messages
MsgObjCollection.Count            // Counts the total number of messages in the object

我不确定如何以最简单、最干净的方式处理这个问题。

注意:如果有任何混淆,这些不是静态方法。我将使用 new 运算符创建这些对象的实例。所以我需要多个实例

最佳答案

这是对 bfavaretto's answer 的一个调整这应该让你更接近你想要的:

function MsgObjCollection() {
    this.sent = [];
    this.received = [];
    this.total = [];

    this.push = function(msg) {
        // Assuming msg.source is either 'sent' or 'received',
        // this will push to the appropriate array.
        this[msg.source].push(msg);

        // Always push to the 'total' array.
        this.total.push(msg);
    };
};

您可以按如下方式使用它:

var coll = new MsgObjCollection();
coll.push(/* whatever */);

var sent = coll.sent.length;
var received = coll.received.length;

如果你愿意,你可以将sentreceived 数组用公开Count 函数而不是length 的对象包装起来 属性;但这让我觉得没必要。

关于javascript - 如何使用我可以推送到的方法和数组制作 Javascript 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17136638/

相关文章:

javascript - 如何使用 JavaScript 将大量数字拆分为 3 组数字?

javascript - 为什么我的倒数计时器不启动和停止?

javascript - PhoneGap 中的 $.getJSON 不工作

javascript - 如何避免在 Webpack 构建中捆绑模拟模块?

javascript - 使用 JQuery 粘贴事件后将焦点更改为下一个输入

javascript - 使用 Jquery 更新图像

javascript - 使用边界矩形获取 d3 元素的高度/宽度时如何考虑比例

javascript - 如何从搜索结果中删除过去的数据并仅显示当前数据

javascript - 使用 javascript 删除子元素

javascript - 不需要的 Json 出现在 html 中