将将类的私有成员设置为构造函数参数
P粉761718546
P粉761718546 2024-04-06 21:48:47
0
1
589

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});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!