Can I use in Google Apps Scripts a defined Class in a library with ES6 (V8)?

后端 未结 2 1094
梦毁少年i
梦毁少年i 2020-12-18 09:44

I\'m trying to use a class defined in a library but I only receive an error as a result.

[LibraryProject]/library/model/Update.gs



        
相关标签:
2条回答
  • 2020-12-18 10:10

    Based on your tests, it appears that you cannot directly import a class from a GAS library. I'd recommend creating a factory method to instantiate the class instead.

    Something along these lines:

    // Library GAS project
    
    /**
     * Foo class
     */
    class Foo {
        constructor(params) {...}
    
        bar() {...}
    }
    
    /* globally accessible factory method */
    function createFoo(fooParams) {
        return new Foo(fooParams);
    } 
    

    // Client GAS project
    
    function test() {
        var foo = FooService.createFoo(fooParams);
        Logger.log(foo.bar());
    }
    
    
    0 讨论(0)
  • 2020-12-18 10:25

    As written in the official documentation,

    Only the following properties in the script are available to library users:

    • enumerable global properties
      • function declarations,
      • variables created outside a function with var, and
      • properties explicitly set on the global object.

    This would mean every property in the global this object are available to library users.

    Before ES6, All declarations outside a function (and function declaration themselves) were properties of this global object. After ES6, There are two kinds of global records:

    • Object record- Same as ES5.

      • Function declarations
      • Function generators
      • Variable assignments
    • Declarative record - New

      • Everything else - let, const, class

    Those in the declarative record are not accessible from the global "object", though they are globals themselves. Thus, the class declaration in the library is not accessible to library users. You could simply add a variable assignment to the class to add a property to the global object(outside any function):

    var Update = class Update{/*your code here*/}
    

    References:

    • Library official documentation
    • Global environment records
    • Related Answers:
      • ES6- What about introspection
      • Do let statements create properties on the global object
    0 讨论(0)
提交回复
热议问题