6

Since Google introduced the V8 engine, I'm migrating some code to the new engine. ES6 allows to define private classes but, when running on Google App Script, I'm getting an error.

Example:

class IncreasingCounter {
  #count = 0;
  get value() {
    console.log('Getting the current value!');
    return this.#count;
  }
  increment() {
    this.#count++;
  }
}

When saving the file, I get the following error:

Error: Line 2: Unexpected token ILLEGAL (line 5075, file "esprima.browser.js-bundle.js")

Any suggestion on how to create a class with Private properties on Google Apps Script (engine V8)?

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • 2
    Class fields are [still stage 3](https://github.com/tc39/proposal-class-fields). The V8 version used by GAS must not be quite as up to date as Chrome's. Perhaps they will update it in a few months once things are completely stable. – CertainPerformance Apr 10 '20 at 00:17
  • You could use a transpiler first if you wanted. You could also do it manually with a WeakMap – CertainPerformance Apr 10 '20 at 00:20
  • see the solution in this entry : https://stackoverflow.com/questions/68044338/declaring-private-variables-in-a-class-google-apps-script-v8 – Stephan Aug 04 '21 at 08:06

1 Answers1

1

Thanks @CertainPerformance for the tip of WeakMaps.

After studying a bit about WeakMaps and Symbols, I found the Symbols solution to be more easy and clean to my case.

So, I end up solving my problem like this:

const countSymbol = Symbol('count');

class IncreasingCounter {
  constructor(initialvalue = 0){
    this[countSymbol]=initialvalue;
  }
  get value() {
    return this[countSymbol];
  }
  increment() {
    this[countSymbol]++;
  }
}

function test(){
  let test = new IncreasingCounter(5);

  Logger.log(test.value);

  test.increment();

  console.log(JSON.stringify(test));
}

As we can confirm, the count property is not listed neither available from outside of the class.