0

I'm trying to make a class GameState with a constructor function to assign my variables. I keep getting the error: Uncaught SyntaxError: Unexpected token 'class' - but all of the documentation I can find says to do it this way. I'm not sure what's wrong. MDN Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

I also found this solution on stack overflow which also looks like what I have, but I'm still getting an error. ES6 Classes: Unexpected token in script?

I tried commenting out all of my code and pasting an example from MDN and it is throwing the same error https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class

Could someone please help me out? I'm pretty new to programming but all of the documentation looks right, I'm still lost. Code below for reference.

class GameState {
    constructor() {
        this.board = [null, null, null, null, null, null, null, null, null];
        this.whoseTurn = 1;
        this.winner = null;
    }
}

let gs = new GameState();

1 Answers1

1

Firstly check the syntax before the class statement as @VLAZ said and put a semicolon if there is not one. Missing semicolons can cause strange errors.

The class statement is a feature new in ES2015. If you are using an older browser (eg. Internet Explorer) this will not work. Instead try a constructor function:

function GameState() {
  if (!(this instanceof GameState)) { //Function was called without the "new" keyword, so we return an instance instead of creating one.
    return new GameState();
  }
  this.board = [null, null, null, null, null, null, null, null, null];
  this.whoseTurn = 1;
  this.winner = null;
}
  
  

let gs = new GameState();

console.log(gs);

You can add prototype functions with GameState.prototype

function GameState() {
  if (!(this instanceof GameState)) { //Function was called without the "new" keyword, so we return an instance instead of creating one.
    return new GameState();
  }
  this.board = [null, null, null, null, null, null, null, null, null];
  this.whoseTurn = 1;
  this.winner = null;
}
  
GameState.prototype.getBoard = function () {
  return this.board;
};

let gs = new GameState();

console.log(gs.getBoard());
ErrorGamer2000
  • 295
  • 3
  • 8
  • Hey guys, I have the same error right now, but in my case class is literally at the very first start of the script.. – Alex Ruhl Sep 15 '21 at 16:49