AndreJacomeSilva
AndreJacomeSilva

Reputation: 99

Define private class fields with Google Apps Scripts (GAS) V8

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)?

Upvotes: 7

Views: 2621

Answers (1)

AndreJacomeSilva
AndreJacomeSilva

Reputation: 99

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.

Upvotes: 1

Related Questions