gpt4 book ai didi

javascript - 如何在谷歌脚本中声明一个自定义类?

转载 作者:行者123 更新时间:2023-12-03 12:33:15 26 4
gpt4 key购买 nike

我想在我的脚本中创建一个类。

Google Apps Script 语言基于 javaScript,所以我从 javaScript 手册中举了一个例子:

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

但是,这不起作用。我收到此错误消息:
Missing ; before statement. (line 1, file "Code")

这是否意味着无法在 google 脚本中创建新类?

还是我应该使用不同的语法?

最佳答案

更新:
自 2020 年 Spring 起,Google 推出了 new runtime适用于支持 Classes 的 Apps 脚本.
新脚本默认使用此运行时,而旧脚本必须转换。脚本编辑器中会显示一个提示,您可以从中转换脚本。

// V8 runtime
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})`);
}
}

const r = new Rectangle(10, 20);
r.logToConsole(); // Outputs Rectangle(width=10, height=20)
原始(旧)答案:
从历史上看,Javascript 是一种“无类”语言,类是尚未被广泛采用的较新功能,并且显然尚未得到 Apps Script 的支持。
下面是如何在 Apps 脚本中模仿类行为的示例:
var Polygon = function(height, width){
this.height = height;
this.width = width;

this.logDimension = function(){
Logger.log(this.height);
Logger.log(this.width);
}
};

function testPoly(){
var poly1 = new Polygon(1,2);
var poly2 = new Polygon(3,4);

Logger.log(poly1);
Logger.log(poly2);
poly2.logDimension();
}

关于javascript - 如何在谷歌脚本中声明一个自定义类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33174024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com