我想定义一个管理消息的 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;
如果你愿意,你可以将sent
和received
数组用公开Count
函数而不是length 的对象包装起来
属性;但这让我觉得没必要。
关于javascript - 如何使用我可以推送到的方法和数组制作 Javascript 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17136638/