Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class private method in newest chrome

I have newest google chrome currently version 80.0.3987.87. I copied example from JS docs which is

class ClassWithPrivateMethod {
  #privateMethod() {
    return 'hello world'
  }

  getPrivateMessage() {
      return #privateMethod()
  }
}

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

and paste it to console. I should get Hello World but instead I have error:

Uncaught SyntaxError: Unexpected token '('

from second line where I declare private method. Why error, what is wrong with my environment? I don't think MDN docs are incorrect..

like image 848
BT101 Avatar asked Feb 05 '20 15:02

BT101


People also ask

Can class methods be private?

The classic way to make class methods private is to open the eigenclass and use the private keyword on the instance methods of the eigenclass — which is what you commonly refer to as class methods.

How do you access private class methods?

We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.

Can I use JS private?

Private fields are currently supported in Node. js 12, Chrome 74, and Babel. A quick recap of ES6 classes is useful before we look at how class fields are implemented.

How do you write a private method?

However, to define a private method prefix the member name with the double underscore “__”. Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.


1 Answers

Update: It is now supported by chrome. the same example will work on chrome devtools if you add this to getPrivateMessage method: 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());
like image 73
Ofir Lana Avatar answered Oct 16 '22 12:10

Ofir Lana