是否有可能每次创建一个对象(使用构建器构建)它都会自动附加到一个空数组?
例如,我有一个客户端构造函数:
function client (firstName, lastName, id, code, balance) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.code = code;
this.balance = balance;
}
和几个例子:
var fred = new client("fred", "sou", 123456, 4545, 2500);
var george = new client("george", "potter", 852564, 5858, 1000);
var will = new client("will", "smith", 475896, 1234, 45000);
我一直在添加客户,我不希望每次注册客户端(创建对象)我都需要 .push 它到我的阵列,像这样:
var fred = new client("fred", "sou", 123456, 4545, 2500);
clientsArray.push(fred);
var george = new client("george", "potter", 852564, 5858, 1000);
clientsArray.push(george);
var will = new client("will", "smith", 475896, 1234, 45000);
clientsArray.push(will);
那么,有没有办法自动定义它?我认为它可能与客户端构造函数有关,但它不是一个普通的方法(因为我必须为我创建的每个对象调用此方法)。
谁有个主意呢?答案 0 :(得分:4)
这样做的一种方法是让阵列原型本身负责注册客户端:
clientsArray.prototype.registerClient = function(firstName, lastName, id, code, balance){
this.push(new client(firstName, lastName, id, code, balance))
};
在此之后,你可以这样做:
clientsArray.registerClient("fred", "sou", 123456, 4545, 2500);
另一种方法是让客户将自己注册到阵列中(考虑责任 - 我认为这似乎不太正确)。在现实生活中,客户/患者是否会直接在医生数据库中注册,或者医生(助理)是否负责注册新客户?最有可能是后者(也许他们必须在患者稍后加入之前进行一些检查)。无论如何,对于这种方法,只需添加:
function client (firstName, lastName, id, code, balance) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.code = code;
this.balance = balance;
clientsArray.push(this);
}
该示例还假设只有一个“singleton”clientsArray。否则你可以将它作为参数传递。我认为第一个版本更干净。
答案 1 :(得分:1)
var clientsArray = [];
function client (firstName, lastName, id, code, balance) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.code = code;
this.balance = balance;
clientsArray.push(this);
}
var fred = new client("fred", "sou", 123456, 4545, 2500);
var george = new client("george", "potter", 852564, 5858, 1000);
var will = new client("will", "smith", 475896, 1234, 45000);
答案 2 :(得分:0)
就个人而言,我认为让另一个方法包装对象的构造是错误的方法,更糟糕的是将它绑定到闭包/全局变量。如果您只需要客户端对象而不是推入阵列,该怎么办?或者如果您的构造函数参数发生了变化?您必须修改包装构造函数的方法和构造函数以使其适合。
我认为你现在遵循的方法是最好的方法,就像这样注入依赖。
clientsArray.push(new client("will", "smith", 475896, 1234, 45000));
但如果你真的必须,你可以添加一个可选参数:
function client (firstName, lastName, id, code, balance, clientsArr) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.code = code;
this.balance = balance;
if(clientsArr) {
clientsArr.push(this);
}
}
然后:
var will = new client('will', 'smith', 475896, 1234, 45000, clientsArray);
如果您不需要推入阵列:
var will = new client('will', 'smith', 475896, 1234, 45000);