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

The lookat() function in three.js isn't functioning according to my requirements

Here is the code snippet I am working with: http://codepen.io/usf/pen/pGscf This is the specific section of interest: function animate() { //sun.rotation.x = t/1000; sun.rotation.y += 0.01; t += 0.1; earth.position.x = Math.sin((2*Ma ...

IBM Watson Conversation and Angular Integration

After recently diving into Angular, I am eager to incorporate a Watson conversation bot into my angular module. Unfortunately, I'm facing an issue with including a library in Angular. To retrieve the Watson answer, I am utilizing botkit-middleware-wat ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

Disregard the popstate triggered by Safari's Initial Page Load

Utilizing pushState, I am able to generate the page view on popstate events based on the history.state of the current page. In cases where there is no history.state present, my intention is to reload the document (hopefully). window.onpopstate = function ...

What is the best way to display a selected checkbox in an AJAX editing modal?

Can someone assist me in loading the checked checkboxes in an edit modal? I am using checkboxes to assign multiple roles in my system. Everything was working fine, but I encountered an issue with my edit modal where the checkboxes appear blank and unchecke ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

Sending user input data to a function in a React component

I am currently facing a challenge where I must retrieve the value of an input field in order to initiate an API request. Here is my current setup: import React, { Component } from 'react' import axios from 'axios'; const fetchWeather ...

Difficulty with implementing authentication middleware based on a condition in Express using Node.js

Currently in the process of developing my website, which includes utilizing an API built with node.js, express, and MongoDb for the database. I am facing a challenge with creating a middleware to ensure that the USER ID matches the POSTED BY ID in a COMME ...

Looking to disable the back button in the browser using next.js?

How can I prevent the browser's back button from working in next.js? // not blocked... Router.onRouteChangeStart = (url) => { return false; }; Does anyone know of a way to disable the browser's back button in next.js? ...

Chrome Extension to Emphasize Every Word

As a novice, I am embarking on the journey of creating my own chrome extension. The idea is to design a popup.html file that showcases a "highlight" button. The functionality would involve clicking this button to highlight all words on the page. Here&apos ...

Which target should be specified for pressing Enter in a Javascript Alert using Selenium IDE?

Seeking assistance with creating simple test cases using Selenium IDE. Encountering difficulties when recording test cases involving Javascript alerts, as Selenium does not support these pop-ups. Attempted a workaround by simulating the Enter key press wh ...

I keep receiving multiple header errors from ExpressJS even though I am positive that I am only sending a single header

Can someone please help with the issue I'm facing in the code below: router.put("/:_id", async (req: Request, res: Response) => { try { // Create the updated artist variable const artist: IArtist = req.body; const updatedArt ...

<a href> click here to append a new query parameter to the existing ones

Is there a way to create a link that will add a query parameter to the current URL instead of replacing all existing ones? Here's what I'm looking for: If the current URL in the browser is example.com/index.html, clicking on it should lead to ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Retrieving the value of a radio button using jQuery and Ajax

Looking for assistance with radio buttons... <input type="radio" id="flip" name="flip" value="Head" checked="checked" /> Head <input type="radio" id="flip" name="flip" value="Tail" /> Tail I'm attempting to process a form with ajax, try ...

Implementing translation text into a PHP database

<!doctype html> <html> <head> <meta charset="utf-8"> <title>Translate and Save Text</title> </head> <body> <form action="" method="post" name="theform"> <table width="693" border="1" style="table-l ...

Submission of the form was cancelled, causing a loop to occur

I'm encountering an issue with submitting a file through a standard HTML form. After uploading the file, the process seems to get trapped in a continuous loop where the file keeps uploading repeatedly. The submission of the form is done using jQuery, ...

Troubleshooting problems with opening and closing windows in JavaScript

I'm currently facing an issue with managing browser windows using JavaScript. In my proof of concept application, I have two pages - one for login information (username, password, login button, etc.) and the second page is a management screen. What I ...

I am interested in redirecting command line output to a file rather than displaying it in the standard

Is it possible to use child-process and spawn in node.js to execute a command and save the output to a file instead of displaying it on the standard output? test.js const expect = require('chai').expect; const { spawn } = require('child_pr ...