首页  >  问答  >  正文

将将类的私有成员设置为构造函数参数

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粉76171854684 天前364

全部回复(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
  • 取消回复