Home  >  Q&A  >  body text

Set a private member of a class as a constructor parameter

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粉761718546P粉761718546202 days ago733

reply all(1)I'll reply

  • P粉010967136

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

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

    reply
    0
  • Cancelreply