【问题标题】:Uncaught SyntaxError: Unexpected token 'class'未捕获的 SyntaxError:意外的标记“类”
【发布时间】:2021-07-01 20:18:57
【问题描述】:

我正在尝试使用构造函数创建一个 GameState 类来分配我的变量。我不断收到错误:Uncaught SyntaxError: Unexpected token 'class' - 但我能找到的所有文档都说要这样做。我不确定出了什么问题。 MDN参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

我还在堆栈溢出上找到了这个解决方案,它看起来也像我所拥有的,但我仍然遇到错误。 ES6 Classes: Unexpected token in script?

我尝试注释掉我的所有代码并从 MDN 粘贴一个示例,它抛出了相同的错误 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class

有人可以帮我吗?我对编程很陌生,但是所有文档看起来都正确,我仍然迷路了。下面的代码供参考。

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

let gs = new GameState();

【问题讨论】:

  • class GameState {前面的代码是什么?
  • 你用的是什么浏览器?
  • 如果您使用的是 Internet Explorer,难怪会出现错误……

标签: javascript


【解决方案1】:

首先检查class语句之前的语法,如@VLAZ所说的,如果没有,则加分号。缺少分号可能会导致奇怪的错误。

class 语句是 ES2015 中的一个新特性。如果您使用的是旧版浏览器(例如 Internet Explorer),这将不起作用。而是尝试构造函数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);

你可以用GameState.prototype添加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());

【讨论】:

  • 嘿伙计们,我现在也有同样的错误,但在我的案例中,类实际上是在脚本的第一次开始......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2013-04-16
  • 2013-01-04
  • 1970-01-01
相关资源
最近更新 更多