0

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 worl​d"

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.

John
  • 1,466
  • 3
  • 21
  • 38
  • Please check the following https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes?page=1&tab=votes#tab-top and https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes?page=2&tab=votes#tab-top – Venkatesh Chitluri Nov 14 '19 at 13:49
  • 1
    Not specific to Chrome apps/extensions as they use the same JavaScript syntax. – wOxxOm Nov 14 '19 at 13:53
  • BTW you can use `get privateMessage()` instead, see [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Prototype_methods). – wOxxOm Nov 14 '19 at 13:54

0 Answers0