Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private static methods in NodeJS v12.13.0 - syntax error

As described in the JavaScript Reference by Mozilla here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields#Private_static_methods

This is how private static methods should work:

class Foo {
  static #privateStaticMethod() {
    return 42;
  }
}

However, when using this in NodeJS v12.13.0, the following syntax error is thrown:

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)

Having a look at the browser compatibility page, private static methods should be supported since v12.

Why is that?

like image 424
j3141592653589793238 Avatar asked Nov 24 '19 13:11

j3141592653589793238


1 Answers

The table states that Private Static fields are supported, not methods.

In node 13.2.0 it's working under --harmony-private-methods flag

[class] implement static private methods was added in v8 7.9. That version of v8 was added to Node 13.2.0


Using the flag, in Node 12.13.0 you won't get a SyntaxError but a TypeError when trying to access the method

TypeError: Read of private field Foo from an object which did not contain the field

v8 issue: Fully implemented behind flag

like image 91
Marcos Casagrande Avatar answered Oct 31 '22 04:10

Marcos Casagrande