首页 > 解决方案 > 最新 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 worl​d"

并将其粘贴到控制台。我应该得到 Hello World 但我有错误:

未捕获的 SyntaxError:意外的标记 '('

从我声明私有方法的第二行开始。为什么会出错,我的环境有什么问题?我不认为 MDN 文档不正确..

标签: javascriptclassoopprivate

解决方案


更新:现在 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());


推荐阅读