gpt4 book ai didi

javascript - 从普通对象创建类实例,无需手动构造函数

转载 作者:行者123 更新时间:2023-11-28 14:29:02 25 4
gpt4 key购买 nike

是否可以从普通对象创建类实例,而无需手动将普通对象值映射到类实例变量?

例如:

class Person {
id;
firstName;
lastName;
age;

fullName() {
return `${this.firstName} ${this.lastName}`;
}
}

const hemmingway = {
id: 1,
firstName: "Ernest",
lastName: "Hemmingway",
age: 62
};

是否可以从 hemmingway 创建一个 Person 类实例,而不必像这样手动映射键:

constructor(plainObject) {
this.id = plainObject.id;
this.firstName = plainObject.lastName;
this.lastName = plainObject.lastName;
this.age = plainObject.age;
}

当尝试将网络 API 响应对象映射到类实例时,这将非常有用。

最佳答案

传递对象后,使用Object.assign将其所有属性分配给实例化:

class Person {
id;
firstName;
lastName;
age;
constructor(plainObject) {
Object.assign(this, plainObject);
}
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}

const hemmingway = {
id: 1,
firstName: "Ernest",
lastName: "Hemmingway",
age: 62
};
const personHemmingway = new Person(hemmingway);
console.log(personHemmingway.fullName());

当然,您也可以在构造函数之外执行此操作:

class Person {
id;
firstName;
lastName;
age;
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}

const hemmingway = {
id: 1,
firstName: "Ernest",
lastName: "Hemmingway",
age: 62
};
const personHemmingway = new Person();
Object.assign(personHemmingway, hemmingway);
console.log(personHemmingway.fullName());

关于javascript - 从普通对象创建类实例,无需手动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52145322/

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