2

I am trying to declare a class with a private variable in Google Apps Script V8 runtime. Here is the code:

class Exam{
  var examName = "";

  getExamName(){
    return this.examName;
  }
}

When I go to save this, I get the following syntax error:

Syntax error: SyntaxError: Unexpected identifier line: 2 file: Code.gs

What am I doing wrong?

TheMaster
  • 45,448
  • 6
  • 62
  • 85

1 Answers1

0

That syntax isn't really valid: https://v8.dev/features/class-fields#es2015-class-syntax

So using the correct syntax, your snippet could become:

class Exam {
  constructor() {
    this._examName = "";
  }
  get examName() {
    return this._examName;
  }
  set examName(value) {
    this._examName = value;
  }
}
mshcruz
  • 1,967
  • 2
  • 12
  • 12
  • Got it. Here is what I am trying to do: class Exam{ constructor(){ this._examName = ""; } getExamName(){ return this.examName; } loadQuestions(examName, sheetDetails){ sheetDetails.values.forEach(function(row, rowId){ this._examName = sheetDetails.values[rowId][3]; } }); } } I now get this error: TypeError: Cannot set property '_examName' of undefined Any help appreciated. Thanks. – Nikhil Karkare Jun 19 '21 at 10:15
  • That is still not following the syntax I posted on my answer. For example, you define a function called "getExamName", but, in the answer, there is a getter whose name is examName(). – mshcruz Jun 19 '21 at 10:30
  • Made the change. Thanks. I am getting an error when setting the internal variable to a value in this._examName = sheetDetails.values[rowId][QBANK_ROUND]; Any idea why that might be happening? – Nikhil Karkare Jun 19 '21 at 10:43
  • You might want to use a setter for that. I updated the answer to include a setter, but I recommend this guide to understand a bit more about classes in JS: https://javascript.info/class#getters-setters – mshcruz Jun 19 '21 at 11:21