4

I'm trying to create a class with some fields on Google Apps Scripts. I can't even save the file. From what I understand of this SO answer, I'm using the correct syntax 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";
}

Rubén
  • 34,714
  • 9
  • 70
  • 166
DBWeinstein
  • 8,605
  • 31
  • 73
  • 118

3 Answers3

6

This is a known issue. Add a star (★ on top left) to the issue, if you want this to be implemented.

https://issuetracker.google.com/issues/195752915

According to the tracker, it is supported, but it is blocked by the parser.

TheMaster
  • 45,448
  • 6
  • 62
  • 85
1

There's a way to simulate static fields in Apps Script. It involves using properties instead of a field. We can create a lazily initiated property that replaces itself with a field, using the following code:

class MyClass {

  static get c() {
    // Delete this property. We have to delete it first otherwise we cannot set it (due to it being a get-only property)
    delete MyClass.c;
    // Replace it with a static value.
    return MyClass.c = {};
  }

}

This approach is better than using a static property, because it also works when instantiating static objects or arrays. To confirm this works, we can use the following:

SpreadsheetApp.getUi().alert(MyClass.c === MyClass.c)

This will only evaluate to true if the object was generated once and stored. If the field remains a property, it will return false, because the object is generated twice.

SonGuhun
  • 121
  • 3
0

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
lochiwei
  • 1,240
  • 9
  • 16