第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何減少屬性分配的輸入(解構(gòu),...)?

如何減少屬性分配的輸入(解構(gòu),...)?

慕勒3428872 2021-06-03 17:51:01
如何減少打字:class C {    Constructor(a,b,c,d,e,f) {       this.a=a;       this.b=b;        this.c=c;        this.d=d;        this.e=e;     }}做這樣的事情:class C {    Constructor(param: [a,b,c,d,e,f]) {       this=param;    }}但這種語法不起作用
查看完整描述

1 回答

?
HUWWW

TA貢獻1874條經(jīng)驗 獲得超12個贊

而是傳入一個對象,然后使用Object.assign:


class C {

  constructor(obj) {

    Object.assign(this, obj);

  }

}


const c = new C({ a: 'a', b: 'b', c: 'c', d: 'd', e: 'e' });

console.log(c);

注意constructor必須是小寫。


您還可以使用參數(shù)休息語法,讓您在調(diào)用時避免重復(fù)new C:


class C {

  constructor(...args) {

    const props = ['a', 'b', 'c', 'd', 'e'];

    const obj = Object.fromEntries(

      args

        .slice(0, 5)

        .map((val, i) => [props[i], val])

    );

    Object.assign(this, obj);

  }

}


const c = new C('a', 'b', 'c', 'd', 'e');

console.log(c);

作為BERGI筆記,你也可以調(diào)用Array.prototype.entries上props的更少的代碼:


class C {

  constructor(...args) {

    const props = ['a', 'b', 'c', 'd', 'e'];

    for (const [i, prop] of props.entries()) {

      this[prop] = args[i];

    }

  }

}


const c = new C('a', 'b', 'c', 'd', 'e');

console.log(c);


查看完整回答
反對 回復(fù) 2021-06-11
  • 1 回答
  • 0 關(guān)注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號