有什么方法可以制作这段代码:
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
看起来与此类似:
function person(first, last, age, eye) {
this = {
firstName: first,
lastName: last,
age: age,
eyeColor: eye
}
}
对于想要优化一切的程序员来说,要初始化许多变量的第一个方法看起来很愚蠢。
最佳答案
使用Object.assign()
方法将对象属性复制到目标对象。
function person(first, last, age, eye) {
Object.assign(this, {
firstName: first,
lastName: last,
age: age,
eyeColor: eye
});
}
关于javascript - 在 JS 对象中初始化此属性的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38738597/