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

huangapple go评论65阅读模式
英文:

set class' private members to constructor arguments

问题

这是一个JavaScript类的代码示例,其中使用了私有字段(Private Fields)。这是一种在类中定义的私有属性,其名称以#字符开头,如#one#two等。私有字段只能在类内部访问,无法从类外部访问。

这种模式的一个解决方案是考虑是否真正需要这么多私有字段。如果有必要,可以将它们分组或组织成更具可读性的结构,以便更轻松地管理和维护代码。

此外,如果某些私有字段在构造函数中初始化并且它们的值在整个类的生命周期内都不会改变,那么可以考虑将它们定义为只读属性(readonly properties)而不是私有字段,以提高代码的可读性。

总之,解决这种模式的关键是审查并优化类的结构,确保代码更易于理解和维护。

英文:
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's a solution to this (anti?) pattern?

答案1

得分: 1

有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});
英文:

Having 16 arguments is no fun for anyone looking to use your constructor. The configuration object idea that you raised in comments is much more interesting, certainly when you combine it with the idea to have one private property of type object that has all these properties. Then you can use Object.assign to have it updated with the user's preferences:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月24日 21:52:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定