首页 > 解决方案 > 我可以在 Google Apps 脚本库中使用 Class 对象吗?

问题描述

我有一个 javascript 类:

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

  myMethod(param1, param2) {
    return param + param2;
  }
}

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

标签: javascriptgoogle-apps-script

解决方案


根据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)
}

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

function myFunction() {
  const r = RectangleLibrary.newRectangle(10, 20);
  r.logToConsole();
}

样本输出:

在此处输入图像描述

在此处输入图像描述


推荐阅读