JavaScript ES6类中的私有属性 [英] Private properties in JavaScript ES6 classes
问题描述
可以在ES6类中创建私有属性吗?
Is it possible to create private properties in ES6 classes?
这是一个例子。
如何阻止访问 instance.property
?
class Something {
constructor(){
this.property = "test";
}
}
var instance = new Something();
console.log(instance.property); //=> "test"
推荐答案
答案是否。但您可以创建私人访问属性,如下所示:
The answer is "No". But you can create private access to properties like this:
- 使用模块。一个模块中的所有内容都是私有的,除非通过使用
export
关键字公开。 - 内部模块使用函数闭包: http://www.kirupa.com/html5/closures_in_javascript.htm
- Use modules. Everything in a module is private unless it's made public by using the
export
keyword. - Inside modules, use function closure: http://www.kirupa.com/html5/closures_in_javascript.htm
(在较早版本的ES6规范中可以使用Symbols来确保隐私的建议,但不再如此: https://mail.mozilla.org/pipermail/es-discuss/2014-January /035604.html 和 https://stackoverflow.com/a/22280202/1282216 。对于更长的时间关于符号和隐私的讨论请参见: https://curiosity-driven.org/private-properties -in-javascript )
(The suggestion that Symbols could be used to ensure privacy was true in an earlier version of the ES6 spec but is no longer the case:https://mail.mozilla.org/pipermail/es-discuss/2014-January/035604.html and https://stackoverflow.com/a/22280202/1282216. For a longer discussion about Symbols and privacy see: https://curiosity-driven.org/private-properties-in-javascript)
这篇关于JavaScript ES6类中的私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!