javascript - 我可以在 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 脚本库并在另一个项目中重用它。这可能吗?
解决方案
根据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();
}
样本输出:
推荐阅读
- reactjs - 无法在名称为“lenghts.byDay”的 TextField 中键入任何字符?
- xml - XQuery 不能按元素名称选择子元素,可以按索引选择
- amazon-lightsail - AWS LightSail 更新启动脚本
- mysql - 错误 #1265 - 无法在默认的“无”字段中插入空值
- ios - 最后一个单元格上的 UITableView beginUpdate 和 endUpdate 重新加载 tableview
- java - 将 (YAML) 文件转换为任何 MAP 实现
- linux - gnu makefile 通过要忽略的文件夹列表过滤源文件列表
- swift - 添加秒到日期的结果是一分钟; 解决方法
- javascript - svg hover 突出显示一个大陆的所有国家
- android - 将对象列表映射到字符串列表