gpt4 book ai didi

javascript - 在 JS 对象中初始化此属性的正确方法

转载 作者:行者123 更新时间:2023-11-29 21:20:10 25 4
gpt4 key购买 nike

我有什么办法可以制作这段代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com