I have a javascript class:
class MyObject {
constructor(arg1, arg2, arg3) {
this.field1 = arg1;
this.field2 = arg2;
this.field3 = arg3;
}
myMethod(param1, param2) {
return param + param2;
}
}
I want to add this class to a Google Apps Script library and reuse it in another project. Is this possible?
As per v8 runtime, classes can now be used in Google Apps Script, either in libraries or standalone scripts. One example is in the documentation:
Classes provide a means to conceptually organize code with inheritance. Classes in V8 are primarily syntactical sugar over the JavaScript prototype-based inheritance.
Declare your class in a script project and deploy as Library. Take note of the script 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)
}
Then in the main app, add the library using the script ID earlier, create an instance and call the method:
function myFunction() {
const r = RectangleLibrary.newRectangle(10, 20);
r.logToConsole();
}
Sample Output:


If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With