搜尋

首頁  >  問答  >  主體

將將類別的私有成員設定為建構函數參數

class Foo {
  #one
  #two
  #three
  #four
  #five
  #six
  #seven
  #eight
  #nine
  #ten
  #eleven
  #twelve
  #thirteen
  #fourteen
  #fifteen
  #sixteen

  constructor(
    one,
    two,
    three,
    four,
    five,
    six,
    seven,
    eight,
    nine,
    ten,
    eleven,
    twelve,
    thirteen,
    fourteen,
    fifteen,
    sixteen
  ) {
    this.#one = one;
    this.#two = two;
    this.#three = three;
    this.#four = four;
    this.#five = five;
    this.#six = six;
    this.#seven = seven;
    this.#eight = eight;
    this.#nine = nine;
    this.#ten = ten;
    this.#eleven = eleven;
    this.#twelve = twelve;
    this.#thirteen = thirteen;
    this.#fourteen = fourteen;
    this.#fifteen = fifteen;
    this.#sixteen = sixteen;
  }
}

這個(反?)模式的解決方案是什麼?

P粉761718546P粉761718546256 天前947

全部回覆(1)我來回復

  • P粉010967136

    P粉0109671362024-04-07 12:15:44

    對於任何想要使用建構函數的人來說,擁有 16 個參數並不有趣。您在評論中提出的配置對像想法要有趣得多,當然,當您將其與擁有具有所有這些屬性的類型對象的私有屬性的想法結合起來時。然後您可以使用 Object.assign 來根據使用者的首選項更新它:

    class Foo {
      #options = {
        one: 1,
        two: 2,
        three: 3,
        four: 4
      }
      constructor(options = {}) {
        Object.assign(this.#options, options);
        console.log(this.#options);
      }
    }
    
    let foo = new Foo({three: 3000});

    回覆
    0
  • 取消回覆