Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a custom class in google scripts?

I want to create a class inside my script.

Google Apps Script language is based on javaScript, so I took an example from a javaScript manual:

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

However, this doesn't work. I get this error message:

Missing ; before statement. (line 1, file "Code") 

Does that mean it's not possible to create new classes in google scripts?

Or is there a different syntax I'm supposed to use?

like image 548
Ada Lovelace Avatar asked Oct 16 '15 15:10

Ada Lovelace


People also ask

What is SS in Google script?

var ss = SpreadsheetApp. This line retrieves the current spreadsheet that's active. Since you're only running this script when the spreadsheet you want to run the calculation on is active, it'll always get the correct spreadsheet. The sheet gets saved as an “object” variable called “ss”.


2 Answers

Update:

As of spring 2020 Google has introduced a new runtime for Apps Script which supports classes. New scripts use this runtime by default, while older scripts must be converted. A prompt is displayed in the script editor from which you can convert your scripts.

Original answer:

Historically Javascript is a "classless" language, classes are a newer feature which haven't been widely adopted yet, and apparently are not yet supported by Apps Script.

Here's an example of how you can imitate class behaviour in Apps Script:

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(); } 
like image 129
Cameron Roberts Avatar answered Sep 23 '22 02:09

Cameron Roberts


TypeScript can now be used with GAS. To use it, download the script files using clasp then convert them to TypeScript by changing the file suffixes to .ts. More info can be found at https://developers.google.com/apps-script/guides/typescript. Once this is done, class can be used.

An example of TypeScript being used to implement Google Sheets custom functions can be found at https://github.com/november-yankee/science-test-grading.

like image 23
Noel Yap Avatar answered Sep 21 '22 02:09

Noel Yap