NodeJS v12.13.0 中的私有静态方法 - 语法错误

use*_*800 6 static static-methods private node.js

正如 Mozilla 的 JavaScript 参考中所述: https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields#Private_static_methods

这就是私有静态方法应该如何工作:

class Foo {
  static #privateStaticMethod() {
    return 42;
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,在 NodeJS v12.13.0 中使用它时,会抛出以下语法错误:

static #privateStaticMethod() {
                             ^

SyntaxError: Unexpected token '('
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:849:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (.../foo.js:8:14)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
Run Code Online (Sandbox Code Playgroud)

查看浏览器兼容性页面,从 v12 开始应该支持私有静态方法。

这是为什么?

Mar*_*nde 5

该表指出支持私有静态字段,而不是方法。

在节点中13.2.0它在--harmony-private-methods标志下工作

[class] v8 中添加了实现静态私有方法7.9。该版本的 v8 已添加到 Node 13.2.0


使用该标志,在 Node 中,当尝试访问该方法时,12.13.0您不会得到 a,SyntaxError而是得到 aTypeError

TypeError: Read of private field Foo from an object which did not contain the field
Run Code Online (Sandbox Code Playgroud)

v8问题: 在flag后面完全实现

  • 我实际上最终使用了箭头函数。它们作为私有静态成员工作:`static #privateStaticMethod = () =&gt; { return 42; };` (3认同)