Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  112] [ 2]  / answers: 1 / hits: 39128  / 9 Years ago, fri, october 16, 2015, 12:00:00

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?


More From » class

 Answers
7

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.


// 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)

Original (old) 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();
}

[#64712] Wednesday, October 14, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
;