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 world"
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..
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.
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With