Set a private member of a class as a constructor parameter
P粉761718546
P粉761718546 2024-04-06 21:48:47
0
1
983

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

What is the solution to this (anti?) pattern?

P粉761718546
P粉761718546

reply all(1)
P粉010967136

For anyone who wants to use a constructor, having 16 parameters is not fun. The configuration object idea you suggested in your comment is much more interesting, of course, when you combine it with the idea of ​​having private properties for a type object that has all those properties. You can then use Object.assign to update it based on the user's preferences:

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});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template