1

I run the following in the Chrome console without problem:


  // Usage:
  //   console.log([...scope]);            // => ['user','script','document']
  //   console.log(`${scope.user`});       // => 'user'
  //   console.log(scope.user.properties); // 'user.properties' (not real code)
  class scope {
    static user = new scope();
    static script = new scope();
    static document = new scope();
    constructor(propertyーscope) {
      if(propertyーscope in scope) return scope[propertyーscope];
    }
    get properties() {
      return `${this.toString()}.properties`; // just for the example
      // in reality, I'd return: 
      // PropertiesService[`get${this.toString().toSentenceCase()}Properties`]();
    }
    static *[Symbol.iterator]() { for (const key of Object.keys(scope)) yield key; }
    toString() { return Object.entries(scope).filter(([key, value])=>value===this)[0][0]; }
  };

However, Google Apps script refuses to save this code snippet and complains about the static declarations (= sign after static user.

  1. Isn't GAS supposed to support static fields?
  2. More importantly, how can I achieve the same?

(note: the dash in propertyーscope is not a dash but a unicode letter looking like it; I use that as a more readable alternative to underscores).

  • I don't think GAS supports static properties, just static methods. See this https://stackoverflow.com/questions/69202290/how-to-use-static-method-in-google-app-script – TheWizEd May 08 '22 at 16:34
  • Does this answer your question? [ParseError: Unexpected token = when trying to save in google Apps Script editor](https://stackoverflow.com/questions/68446467/parseerror-unexpected-token-when-trying-to-save-in-google-apps-script-editor) – Iamblichus May 09 '22 at 07:15

1 Answers1

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 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 = new StaticObject();
  }

}

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.

SonGuhun
  • 121
  • 3