Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Class objects in Google Apps Script Libraries?

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?

like image 433
Lewis Avatar asked Jul 18 '26 19:07

Lewis


1 Answers

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

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:

enter image description here

enter image description here

like image 159
CMB Avatar answered Jul 21 '26 07:07

CMB



Donate For Us

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