BT1*_*101 7 javascript oop private class
我有最新的谷歌浏览器当前版本 80.0.3987.87。我从 JS 文档中复制了示例,它是
class ClassWithPrivateMethod {
#privateMethod() {
return 'hello world'
}
getPrivateMessage() {
return #privateMethod()
}
}
const instance = new ClassWithPrivateMethod()
console.log(instance.getPrivateMessage())
// expected output: "hello worl?d"
Run Code Online (Sandbox Code Playgroud)
并将其粘贴到控制台。我应该得到 Hello World 但我有错误:
未捕获的语法错误:意外的标记 '('
从我声明私有方法的第二行开始。为什么出错,我的环境有什么问题?我不认为 MDN 文档不正确..
据我所知,该提案仍处于第 3 阶段,
您可以在此处查看开发历史和状态
以了解有关该过程的更多详细信息
MDN 仅表示 chrome 支持私有类字段
而不是方法。
这就是你得到错误的原因。
但是,正如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());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
937 次 |
最近记录: |