我可以在 Google Apps 脚本库中使用类对象吗?

Lew*_*wis 7 javascript google-apps-script

我有一个 javascript 类:

class MyObject {
  constructor(arg1, arg2, arg3) {
    this.field1 = arg1;
    this.field2 = arg2;
    this.field3 = arg3;
  }

  myMethod(param1, param2) {
    return param + param2;
  }
}
Run Code Online (Sandbox Code Playgroud)

我想将此类添加到 Google Apps 脚本库并在另一个项目中重用它。这可能吗?

CMB*_*CMB 8

根据v8 运行时,现在可以在 Google Apps 脚本中使用类,无论是在库中还是在独立脚本中。文档中有一个示例:

课程

类提供了一种通过继承在概念上组织代码的方法。V8 中的类主要是 JavaScript 基于原型的继承的语法糖。

在脚本项目中声明您的类并部署为库。记下脚本 ID。

class Rectangle {
  constructor(width, height) { // class constructor
    this.width = width;
    this.height = height;
  }

  logToConsole() { // class method
    console.log(`Rectangle(width=${this.width}, height=${this.height})`);
  }
}

function newRectangle(width, height) {
  return new Rectangle(width, height)
}
Run Code Online (Sandbox Code Playgroud)

然后在主应用程序中,使用之前的脚本 ID 添加库,创建实例并调用方法:

function myFunction() {
  const r = RectangleLibrary.newRectangle(10, 20);
  r.logToConsole();
}
Run Code Online (Sandbox Code Playgroud)

示例输出:

在此输入图像描述

在此输入图像描述