最新版Chrome中的类私有方法

7

我目前使用最新版的 Google 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文档有误。


3
我认为 MDN 文档并不是错误的,至少它们是不完整的。对于私有类方法(与普通字段分开)没有兼容性表格,并且显然它们在您的 Chrome 版本中不受支持。 - Bergi
方法名称可以以 # 开头吗?请参考 https://mathiasbynens.be/notes/javascript-identifiers。 - Pramod S. Nikam
2个回答

7

更新: 现在chrome已经支持该特性。 如果你在getPrivateMessage方法中添加this,相同的示例将在chrome devtools上运行: getPrivateMessage() { return this.#privateMethod(); }

As far as I can tell the proposal is still just stage 3
you can check here Development history & status
for more details about the process
MDN only says that chrome supports private class fields not methods.
That's the reason you get an error.
However, as mentioned private fields are supported by chrome and you can use something similar to that :

class ClassWithPrivateMethod {
  #privateMethod

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

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


你能提供一些描述吗?你的意思是什么? - BT101
好的,请稍等一下。 - Ofir Lana
希望这对你有所帮助,如果不行的话,随时可以问更多的问题。 - Ofir Lana
它说在node.js v12中有完全支持,但经过我测试后发现并不是这样。 - user192344

0

请尝试以下方法

  • 使用箭头函数
  • 在调用方法的地方,使用this.#methodName()
  • 因此,您需要将这行代码return #privateMethod()更正为return this.#privateMethod()
  • 这也适用于nodejs v12.0.00以上版本

class ClassWithPrivateMethod {
  #privateMethod = () => {
    // use arrow function
    return 'hello world'
  }

  getPrivateMessage() {
      return this.#privateMethod()
  }
}

const instance = new ClassWithPrivateMethod()
console.log(instance.getPrivateMessage())
// expected output: "hello worl​d"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接