Legen Sie ein privates Mitglied einer Klasse als Konstruktorparameter fest
P粉761718546
P粉761718546 2024-04-06 21:48:47
0
1
979

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;
  }
}

Was ist die Lösung für dieses (Anti-?)Muster?

P粉761718546
P粉761718546

Antworte allen(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});
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage