javascript - 最新 chrome 中的类私有方法
问题描述
我有最新的谷歌浏览器当前版本 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 world"
并将其粘贴到控制台。我应该得到 Hello World 但我有错误:
未捕获的 SyntaxError:意外的标记 '('
从我声明私有方法的第二行开始。为什么会出错,我的环境有什么问题?我不认为 MDN 文档不正确..
解决方案
更新:现在 chrome 支持它。this
如果您添加到 getPrivateMessage 方法
,相同的示例将适用于 chrome devtools : getPrivateMessage() { return this.#privateMethod(); }
据我所知,该提案仍只是第 3 阶段
,您可以在此处查看Development history & status
以了解有关该过程的更多详细信息
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());
推荐阅读
- python-3.x - 尝试 Tornado Websockets 服务器的参数化单元测试
- c# - 使用 javascript 客户端应用程序连接到 Winforms 应用程序
- javascript - 我有一个应该是对象的数组
- cypress - Cypress.io 最佳实践,常用选择器支持文件?
- html - 显示离子段按钮,除了第一个按钮
- python - 在具有 virtualenv 的项目中无法识别 Pip 和 Python
- mysql - 多值的数据类型是什么:SQL 中的字符串列表?
- java - 在最简单的情况下,VM 是否会跳过自动装箱-拆箱?
- asp.net-mvc - 在 nginx 反向代理后面设置 ASP NET Core MVC 应用程序的虚拟路径
- php - 如何在php中修复未设置的json对象