【问题标题】:Class private method in newest chrome最新 chrome 中的类私有方法
【发布时间】:2020-05-21 13:16:57
【问题描述】:

我有最新的谷歌浏览器当前版本 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 文档不正确..

【问题讨论】:

  • "我不认为 MDN 文档不正确。" - 至少它们是不完整的。私有类方法(与普通字段分开)没有兼容性表,显然您的Chrome版本不支持它们。
  • can # 允许作为方法名称的开头mathiasbynens.be/notes/javascript-identifiers?

标签: javascript class oop private


【解决方案1】:

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

据我所知,该提案仍只是第 3 阶段
你可以在这里查看Development history & status
有关该过程的更多详细信息
MDN 只说 chrome 支持私有类 fields 不是方法
这就是您收到错误的原因。
但是,如前所述 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());

【讨论】:

  • 你能提供一些描述吗?什么意思?
  • 是的,请稍等
  • 希望对您有所帮助,如果不能随时提出更多问题
  • 它说完全支持 node.js v12,这不是在我测试之后
猜你喜欢
  • 2014-03-25
  • 2017-05-23
  • 2010-09-15
  • 1970-01-01
  • 2021-04-27
  • 2018-03-01
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
相关资源
最近更新 更多