具有计算名称的私人课程成员

发布于 2025-01-20 23:55:51 字数 973 浏览 2 评论 0原文

使用现代 javascript,我们可以在类上拥有私有成员

  class someClass {
    #privateField = 'foo'
    #privateMethod() { ... }
  }

  const instance = new someClass(); // #privateField and #privateMethod are not accessible on the instance
  someClass.#privateField; // SyntaxError: Private field '#priv' must be declared in an enclosing class

一段时间以来,我们已经能够通过使用计算值来拥有名称不是有效标识符的字段(例如包含空格、符号、以数字开头等),例如

  class someClass {
    ["member name that would otherwise be invalid"](){ ... } 
  }

是吗?可以将两者混合并拥有​​具有计算名称的私有成员吗?

例如,

  class someClass {
    ["#private Member with invalid name"]() { ... } // this is not actually private
    #["private Member with invalid name"]() { ... } // this is not valid syntax
  }

我正在编写生成其他代码的代码(是的,我知道注入风险。请放心,我会适当处理它们)。我可以相当确定我需要创建的成员不会具有作为标识符有效的名称,因此我需要使用计算属性名称语法。但我也希望他们成为私人会员。

我可以使用多种解决方法,包括使用符号、修改或混淆名称,甚至按惯例保密。

我希望有一个比这些更优雅的解决方案。

With modern javascript we can have private members on classes

  class someClass {
    #privateField = 'foo'
    #privateMethod() { ... }
  }

  const instance = new someClass(); // #privateField and #privateMethod are not accessible on the instance
  someClass.#privateField; // SyntaxError: Private field '#priv' must be declared in an enclosing class

For some time we've been able to have fields with names that are not valid identifiers (e.g. contains spaces, symbols, start with a number, etc.) by using computed values e.g.

  class someClass {
    ["member name that would otherwise be invalid"](){ ... } 
  }

Is it possible to mix the 2 and have private members with computed names?

e.g.

  class someClass {
    ["#private Member with invalid name"]() { ... } // this is not actually private
    #["private Member with invalid name"]() { ... } // this is not valid syntax
  }

I am writing code that generates other code (yes, I am aware of injection risks. Rest assured that I will handle them appropriately). I can be reasonably sure that the members I need to create will not have names that are valid as identifiers, hence I need to use the computed property name syntax. But I also want them to be private members.

There are numerous workarounds I could use including using symbols, mangling or obfuscating the names, or even private-by-convention.

I am hoping for a solution that is more elegant than any of these.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文