类似“ this.uuid = uuid ...”的构造看起来很丑。我该怎么写呢?
好像不是最好的方法。
function account({
uuid,
email,
pass,
device_id,
max_rep = 10,
max_like = 10,
max_comm = 10,
max_sub = 10
}) {
this.uuid = uuid;
this.email = email;
this.pass = pass;
this.device_id = device_id;
this.max_rep = max_rep;
this.max_like = max_like;
this.max_com = max_comm;
this.max_sub = max_sub;
}
a = new account({
uuid: '12',
email: "g@mail.ru",
pass: "123",
device_id: "444"
})
b = new account({
uuid: '13',
email: "ab@mail.ru",
pass: "456",
device_id: "777"
})
console.log(a,b)
答案 0 :(得分:2)
您可以破坏道具,然后从道具中生成一个对象,并将其分配给this
:
function account({
uuid,
email,
pass,
device_id,
max_rep = 10,
max_like = 10,
max_comm = 10,
max_sub = 10
}) {
Object.assign(this, {
uuid,
email,
pass,
device_id,
max_rep,
max_like,
max_comm,
max_sub
});
}
const a = new account({
uuid: '12',
email: "g@mail.ru",
pass: "123",
device_id: "444"
})
const b = new account({
uuid: '13',
email: "ab@mail.ru",
pass: "456",
device_id: "777"
})
console.log(a)
console.log(b)
答案 1 :(得分:0)
在函数中创建一个新对象,然后分配其属性并返回:
function account(obj) {
const act = {};
for (let [key, value] of Object.entries(obj)){
act[key] = value;
}
["max_rep", "max_like", "max_comm", "max_sub"].forEach((prop) => {
act[prop] = obj[prop] ? obj[prop] : 10;
})
return act;
}
const a = account({
uuid: '12',
email: "g@mail.ru",
pass: "123",
device_id: "444",
max_rep: "123"
})
const b = account({
uuid: '13',
email: "ab@mail.ru",
pass: "456",
device_id: "777"
})
console.log(a, b)