如何在javascript对象中使用构造函数以仅使用`this`中的属性?

时间:2019-04-23 18:38:25

标签: javascript typescript

我想创建以下类的实例:

class Person {
    firstName;
    lastName;
    birthday;
    constructor(props: Person) {
        {firstName,lastName,birthday} = props
    }
}

var me = new Person({firstName: "donald", 
lastName: "trump",
 middleName: "john"})

我希望构造函数只选择要分配给“ this”的类的属性,这样me将是{firstName: "donald", lastName: "trump", birthday: undefined}

我的想法是这样做:

class Person {
    firstName;
    lastName;
    birthday;
    constructor(props: Person) {
        this.{firstName,lastName,birthday} = props
    }
}

var me = new Person({firstName: "donald", lastName: "trump", middleName: "john"})

或类似的东西。

1 个答案:

答案 0 :(得分:4)

您可以分为两行:

const {firstName,lastName,birthday} = props;
Object.assign(this, {firstName,lastName,birthday});

现在,如果这只是关于三个属性,请执行以下操作:

this.firstName = props.firstName;
this.lastName = props.lastName;
this.birthday = props.birthday;

它更具可读性,并且速度更快。值得多加一行。

您还可以更改构造函数签名,以便对所需的属性进行解构:

constructor({firstName: string, lastName: string, birthday: Date}) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthday = birthday;
}