簡體   English   中英

如何在 JavaScript 中將對象傳播到類屬性中

[英]How to spread an object into a classes properties in JavaScript

基本上這就是我想要完成的。

 class Person { constructor (obj) { this.first = '' this.last = '' this.age = '' if (obj) { Object.assign(this, ...obj) } } } const a = new Person() console.log('Not spreading: ', a) const b = new Person({ first: 'Alex', last: 'Cory', age: 27 }) console.log('Spreading: ', b)

有沒有辦法傳播這樣的對象來填充一個類?

如果您使用的是Object.assign ,則不使用擴展表示法; 只需刪除...

 class Person { constructor (obj) { this.first = '' this.last = '' this.age = '' if (obj) { Object.assign(this, obj) // <============ No ... } } } const a = new Person() console.log('Not spreading: ', a) const b = new Person({ first: 'Alex', last: 'Cory', age: 27 }) console.log('Spreading: ', b) 

有一個提議 (目前處於第3階段,很可能在ES2018中,並得到轉發器的廣泛支持),它在對象初始化器中對象屬性傳播,但這不適用於對象已存在的情況。

您可以使用解構並僅使用您需要的屬性。

 class Person { constructor ({ first = '', last = '', age = '' } = {}) { Object.assign(this, { first, last, age }); } } const a = new Person() console.log('Not spreading: ', a) const b = new Person({ first: 'Alex', last: 'Cory', age: 27, foo: 42 }) console.log('Spreading: ', b) 

這是你在找什么?

 class Person { constructor (obj) { this.firstName = '' this.lastName = '' this.age = '' if (obj) { Object.assign(this, obj) } } } const a = new Person() console.log('Not spreading: ', a) const b = new Person({ firstName: 'Alex', lastName: 'Cory', age: 27 }) console.log('Spreading: ', b) 

我個人更喜歡使用單獨的方法,因為在 JS 中不可能有多個構造函數。 在以下示例中,我使用返回新對象的static fromObject()方法創建新對象。 因此,您可以保留普通構造函數並使用擴展語法創建新對象。

注意:我在這里使用打字稿。

export class Point {
    readonly x: number
    readonly y: number

    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }

    static fromObject({x, y}: {x: number, y: number}) {
        return new Point(x, y)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM