我有最新的谷歌浏览器当前版本 80.0.3987.87。我复制了example from JS docs这是
class ClassWithPrivateMethod {
#privateMethod() {
return 'hello world'
}
getPrivateMessage() {
return #privateMethod()
}
}
const instance = new ClassWithPrivateMethod()
console.log(instance.getPrivateMessage())
// expected output: "hello world"
并将其粘贴到控制台。我应该得到 Hello World 但我有错误:
Uncaught SyntaxError: Unexpected token '('
从我声明私有(private)方法的第二行开始。为什么会出错,我的环境有什么问题?我不认为 MDN 文档不正确..
最佳答案
更新 : 现在 chrome 支持了。
如果您添加 this
,相同的示例将适用于 chrome devtools getPrivateMessage 方法: getPrivateMessage() { return this.#privateMethod(); }
据我所知,该提案仍只是第 3 阶段
你可以在这里查看Development history & status
有关该过程的更多详细信息
MDN 只说 chrome 支持私有(private)类 字段
不是 方法 .
这就是您收到错误的原因。
然而,正如提到的 private fields
受chrome支持,您可以使用
类似的东西:
class ClassWithPrivateMethod {
#privateMethod
constructor(){
this.#privateMethod = function(){
return 'hello world';
};
}
getPrivateMessage() {
return this.#privateMethod();
}
}
const instance = new ClassWithPrivateMethod();
console.log(instance.getPrivateMessage());
关于javascript - 最新 chrome 中的类私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60078943/