Class 最新的私有方法 chrome

Class private method in newest chrome

我有最新的 google chrome 当前版本 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 worl​d"

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

Uncaught SyntaxError: Unexpected token '('

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

更新:chrome现已支持。 如果将 this 添加到 getPrivateMessage 方法,则相同的示例将适用于 chrome devtools: getPrivateMessage() { return this.#privateMethod(); }

据我所知,提案仍处于第 3 阶段
你可以在这里查看 Development history & status
有关该过程的更多详细信息
MDN 只说 chrome 支持 private class fields 不是 方法 .
这就是您出错的原因。
但是,如前所述,chrome 支持 private fields,您可以使用 类似的东西:

class ClassWithPrivateMethod {
  #privateMethod

  constructor(){
      this.#privateMethod = function(){
          return 'hello world';
      };
  }

  getPrivateMessage() {
      return this.#privateMethod();
  }
}
const instance = new ClassWithPrivateMethod();
console.log(instance.getPrivateMessage());