將將類別的私有成員設定為建構函數參數
P粉761718546
P粉761718546 2024-04-06 21:48:47
0
1
828

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粉761718546
P粉761718546

全部回覆(1)
P粉010967136

對於任何想要使用建構函數的人來說,擁有 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});
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板