Creating a personalized class in Google Apps Script: a step-by-step guide

I'm trying to define a new class within my Google Apps Script.

Even though the language is based on JavaScript, I encountered an issue while using an example from a JavaScript manual:

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

Unfortunately, it didn't work as expected and displayed the following error message:

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

Does this mean that creating new classes in Google Scripts is not supported?

Alternatively, should I be using a different syntax for this purpose?

Answer №1

Update:

Recently, in the spring of 2020, Google unveiled a new runtime for Apps Script that now includes support for Classes.
New scripts automatically utilize this updated runtime, while older scripts require conversion. A conversion prompt will appear in the script editor to guide you through the process.

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

Traditionally, Javascript has been considered a "classless" language, as classes are a relatively newer concept that hasn't been widely embraced yet, and still aren't fully supported by Apps Script.

Here's how you can simulate class-like behavior 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();
}

Answer №2

Google Apps Script now supports the use of TypeScript. By downloading the script files with clasp and converting them to TypeScript by changing the file extensions to .ts, users can take advantage of this feature. For more details, visit https://developers.google.com/apps-script/guides/typescript. Once the conversion is complete, developers can utilize the class functionality.

To see an example of using TypeScript for implementing custom functions in Google Sheets, check out https://github.com/november-yankee/science-test-grading.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with setting background image height to 100% or 100vh

Seeking help to address the issue of the URL field impacting the total height. Any assistance would be greatly appreciated. body,html { height:100% } Issue arises when there is a display in the address bar. .bg { min-height:100% background-size: cover; ...

Modifying the color of a non-active tab - Material UI Tabs

Is there a way to customize the color of inactive tabs in Material UI tabs? I have noticed that they currently appear black, as shown in the screenshot here: screenshot Thank you! ...

Could not complete operation: EPERM error indicating permission denied for 'stat' operation

Recently delving into Firebase Functions for my Flutter project has been a game-changer. Discovering the code generator, firebase_functions_interop, that seamlessly transforms Dart code into Javascript has made developing cloud functions in Dart a breeze. ...

Error: Authorization required to access server-side resource [POST http://localhost:3000/serverSide] - Status

I'm having an issue with sending a username and password from an HTML file to a Javascript file that queries an employee table for authentication. The problem arises when the username and password are set to undefined in my serverSide.js file, prevent ...

Is it feasible to generate a fixed lighting effect overlay with HTML and CSS?

Is it possible to incorporate a static lighting effect overlay using HTML/CSS? My project consists of an HTML5/JS app with a top navigation bar and a series of cards that are transitioned through using swipe gestures. These cards are displayed in gray ove ...

Minimize the amount of external asynchronous calls made by the client

In my application, the client initiates multiple asynchronous JavaScript requests to third party servers. The issue I'm encountering is that when the client responds to these requests, the site becomes inactive for a brief period of time. This inactiv ...

Comparison of Uint8Array and Uint8ClampedArray

Can you explain the distinction between Uint8Array and Uint8ClampedArray within JavaScript? I've heard that Uint8ClampedArray is specifically utilized for pixel manipulations on canvas. Could you elaborate on why this array type is recommended for suc ...

Building Firestore subcollections with the latest WebSDK 9: A step-by-step guide

I'm looking to create a subcollection within my document using the webSDK 9, specifically the tree-shakable SDK. While I have come across some solutions, they all seem to be outdated and reliant on the old sdk. Just for context, I am working with Ne ...

Is there a way to seamlessly integrate typeahead.js with jquery.validate?

Currently, I have a website built on ASP.NET MVC 5 which utilizes jQuery validation (specifically 'jquery.validate.js' in the MVC project template). My goal is to implement type-ahead functionality using 'typeahead.js' on an input field ...

Is there a way to remove a row through fetch using onclick in reactjs?

I'm completely new to this and struggling with deleting a row using fetch. I've written some messy code and have no idea if it will even work. Please help, I feel so lost... renderItem(data, index) { return <tr key={index} > &l ...

Issue with refreshing a material

When updating a transaction, I am encountering the issue of inadvertently deleting other transactions. My goal is to update only one transaction. Can someone review my backend logic to identify the root cause? Schema Details: const mongoose = require(&apo ...

Exploring JSON Data with NativeScript

As a newcomer to NativeScript and JSON, I am currently facing challenges in accessing data from my JSON file. My main goal right now is to simply log some of the data for debugging purposes. Below is the code snippet from my view-model: var config = requ ...

Sort the data in Angular JS by one key, but ensure that results with another key set to 0 remain at the end

Here is an array of objects containing information about various car brands: $scope.cars = [ {"brand":"McLaren","price":70,"stock":0}, {"brand":"Renault","price":10,"stock":0}, {"brand":"Ferrari","price":100,"stock":3}, {"brand":"Lamborghini","pri ...

Issue encountered: Unforeseen command: POST karma

Whenever I try to run my test cases, I encounter the following error message: Error: Unexpected request: POST data/json/api.json it("should $watch value", function(){ var request = '/data/json/api.json'; $httpBackend.expectPOST(reque ...

How can you iterate over the input elements that are currently visible within a form using Javascript?

Is there a way to clear the values of all visible input fields in a form using JavaScript? I'm currently struggling with setting text inputs to empty as they come out as undefined. Any suggestions on how to achieve this? ...

The functionality of sending form data via Express.js router is restricted

In my current project, I am developing a basic CRUD functionality in express. My goal is to utilize the express.Router() to transmit form data via the HTTP POST method. The form structure on the browser appears as follows: form.png The process was flawle ...

Loading data dynamically in the Highcharts ng library allows for real-time updates to the

I'm currently working on integrating highcharts ng into my Angular project, but I'm encountering issues with data not populating. It seems like there might be a problem related to the loading of the DOM and the function call. Here's my HTML ...

Exploring time differences in Javascript

I am trying to save a JSON AJAX response from the server in the browser's localStorage for a duration of one minute, along with a timestamp generated using new Date().getMinutes(). Upon triggering $(document).ready, I aim to check the stored timestam ...

The crosshair functionality in Zing Chart is causing a CPU leak

After enabling the crosshair feature on my chart, I noticed a significant issue when using Chrome 57 (and even with versions 58 and ZingChart 2.6.0). The CPU usage spikes above 25% when hovering over the chart to activate the crosshair. With two charts, th ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...