是否可以从普通对象创建类实例,而无需手动将普通对象值映射到类实例变量?
例如:
class Person {
id;
firstName;
lastName;
age;
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const hemmingway = {
id: 1,
firstName: "Ernest",
lastName: "Hemmingway",
age: 62
};
是否有可能从Person
中创建一个hemmingway
类实例,而不必像这样手动映射键:
constructor(plainObject) {
this.id = plainObject.id;
this.firstName = plainObject.lastName;
this.lastName = plainObject.lastName;
this.age = plainObject.age;
}
当尝试将网络API响应对象映射到类实例时,这将非常有用。
答案 0 :(得分:4)
传递对象后,使用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());