Javascript SpiderMonkey SyntaxError: missing : after propert

Javascript SpiderMonkey SyntaxError: missing : after property id:

本文关键字:after propert missing Javascript SyntaxError SpiderMonkey      更新时间:2023-09-26

我正在使用蜘蛛猴制作一个简单的控制台国际象棋游戏。但是,我的枚举声明中不断收到错误SyntaxError: missing : after property id:

SyntaxError: missing : after property id:
ChessPiece.js:4:5      var Color = {
ChessPiece.js:4:5 ............^

这是完整的代码

class ChessPiece
{
    var Color = {
        WHITE : 'W',
        BLACK : 'B'
    };
    var Piece = {
        PAWN : 'P',
        ROOK : 'R',
        KNIGHT : 'N',
        BISHOP : 'B',
        QUEEN : 'Q',
        KING : 'K'
    };
    constructor(color, piece)
    {
        this.color = color;
        this.piece = piece;
    }
    toString()
    {
        return this.color + this.piece;
    }
}

编辑:更新了枚举语法作为变量声明。

我想枚举不能在类体内定义。我能够在类定义之后添加它们。

class ChessPiece
{
    constructor(color, piece)
    {
        this.color = color;
        this.piece = piece;
    }
    toString()
    {
        return this.color + this.piece;
    }
}
ChessPiece.Color = {
    WHITE : 'W',
    BLACK : 'B'
};
ChessPiece.Piece = {
    PAWN : 'P',
    ROOK : 'R',
    KNIGHT : 'N',
    BISHOP : 'B',
    QUEEN : 'Q',
    KING : 'K'
};

正确答案在这里:

js 类实例属性

静态类端属性和原型数据属性必须是 在类体声明之外定义

实例变量必须在构造函数中使用"this"声明。