是否可以在 ES6 类中创建私有属性?
这是一个例子。如何防止访问instance.property?
instance.property
class Something { constructor(){ this.property = "test"; } } var instance = new Something(); console.log(instance.property); //=> "test"
私有类功能在第 3 阶段提案中。所有主要浏览器都支持其大部分功能。
class Something { #property; constructor(){ this.#property = "test"; } #privateMethod() { return 'hello world'; } getPrivateMessage() { return this.#property; } } const instance = new Something(); console.log(instance.property); //=> undefined console.log(instance.privateMethod); //=> undefined console.log(instance.getPrivateMessage()); //=> test console.log(instance.#property); //=> Syntax error