How to declare Class fields in Google App Script using javascript

Viewed 303

I'm trying to create a class with some fields on Google Scripts. I can't even save the file. From what I understand of this SO answer, I'm using the correct syntac for class fields.

V8 runtime is enabled.

The error:

Syntax error: ParseError: Unexpected token = line: 5 file: Airtable_Class.gs

Line 5 is: foo = "bar";

Here's the whole code:

class FieldsTest{
  foo = "bar";
}

2 Answers

Although it seems that Google Apps Script doesn't support static class fields, it does support static methods/getters/setters, so you can do this:

class X {
   // ⭐️ static getters & setters
   static get a(){ return this._a || 0 }     // this === X
   static set a(value){ this._a = value }    // this === X
}

then you can get/set X.a as usual:

X.a      // get: 0.0
X.a = 3  // set: 3.0
X.a      // get: 3.0
Related