I am refactoring an existing Chrome Packaged App and it now uses ES6 Classes. I want to make some of the methods of the class private. The MDN documentation has an example for this:
class ClassWithPrivateMethod {
#privateMethod() {
return 'hello world';
}
getPrivateMessage() {
return #privateMethod();
}
}
const instance = new ClassWithPrivateMethod();
console.log(instance.getPrivateMessage());
// expected output: "hello world"
When wrap this example code into a Chrome Packaged App the app refuses to run, I instead see:
Uncaught SyntaxError: Unexpected token '('
This is reported against line 2: #privateMethod(){
However, if I go to an earlier example that uses private instance fields:
class ClassWithPrivateField {
#privateField;
constructor() {
this.#privateField = 42;
this.#randomField = 666; # Syntax error
}
}
const instance = new ClassWithPrivateField();
instance.#privateField === 42; // Syntax error
When wrapped as a Chrome Packaged App this code snippit does produce the expected result.
Therefore my questions are:
- Am I supposed to be able to use private instance methods in my Chrome Packaged Apps?
- Is this a bug (I think it is so I posted here) or is this designed/desired behaviour?
- Has anybody else been able to use private instance methods in their development of Chrome Packaged Apps?
- Is there a different technique I can use to make certain methods of a class private?
UPDATE 2019-11-14:
I got a workaround but not one that I'm particularly happy with:
class ClassWithPrivateMethod {
#privateMethod
constructor(){
this.#privateMethod = function(){
return 'hello world';
};
}
getPrivateMessage() {
return this.#privateMethod();
}
}
const instance = new ClassWithPrivateMethod();
console.log(instance.getPrivateMessage());
By making #privateMethod
a private field of the class and then using the constructor to assign it a function I can create a private method however this means declaring all of my function code inside the constructor which would make it messy and difficult for any future developers to read.