2

I attempted to use Private class features in Google Apps Script, using the following snippet:

class Feed
{
  #user;
  #password;
  url;
  
  constructor(url, credentials)
  {
    // class constructor
    this.url = url;
    this.#user = credentials.user;
    this.#password = credentials.password;
  }
}

with the intention of calling it in the following manner:

const url = "https://URL"
const credentials = {user: 'user', password: 'password'};

let feed = new Feed(url, credentials);

On saving the file, the following error was displayed, appearing to indicate that private class features aren't supported in Google Apps Script:

Syntax error: ParseError: Unexpected token ILLEGAL line: 3 file: Testing.gs

I removed the '#' on line three, as shown below:

class Feed
{
  user;
  #password;
  url;
  
  constructor(url, credentials)
  {
    // class constructor
    this.url = url;
    this.#user = credentials.user;
    this.#password = credentials.password;
  }
}

and received the following error on saving:

Syntax error: SyntaxError: Private field '#user' must be declared in an enclosing class line: 11 file: Testing.gs

I searched, and found Define private class fields with Google Apps Scripts (GAS) V8 which indicated that (at the time) private class features weren't supported in Google Apps Script. While the first error message seems to confirm that this is the case, the second implies that Apps Script understands private class fields.

Questions:

  • Are private class fields supported by Google Apps Script (v8)?
  • If so, how are they supposed to be implemented?

Thanks,

Fergal

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • 1
    Private class fields are probably not supported yet (even though the error suggests otherwise). You can fallback on using closures and `WeakMap`s for the time being. – TheAddonDepot Jul 20 '22 at 18:22
  • 1
    I reported the inconsistent error messaging via https://issuetracker.google.com/issues/239767510. We'll see what they come back with. – Fergal Moore Jul 21 '22 at 10:57
  • 1
    Confirmed as a known issue, and something that they are working on, but not available yet. – Fergal Moore Jul 21 '22 at 14:14
  • @TheAddonDepot Can those same workarounds be used for methods as well? – Robert M. Jul 02 '23 at 00:33
  • 1
    @RobertM. Yup. You can define the equivalent of a private method using closures. That's pretty much how its always been done. It's only within the last few years that Javascript gained native support for features such as Classes; and even then its just syntactic sugar, the language still uses Prototypal Inheritance under the hood. – TheAddonDepot Jul 02 '23 at 13:30
  • @TheAddonDepot Thank you sir. in a sense all high level languages are syntactic sugar, it's all machine code under the hood. – Robert M. Jul 03 '23 at 15:58

0 Answers0