具有计算名称的私人课程成员
使用现代 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论