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

时间:2018-09-03 07:48:31

标签: javascript

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

例如:

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响应对象映射到类实例时,这将非常有用。

1 个答案:

答案 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());