获得无效的退货声明'而且我不确定为什么

时间:2014-07-14 23:25:38

标签: javascript

我正致力于编写Conway's Game of Life grid

我是JavaScript的新手,我正在尝试向棋盘对象添加一个方法,该方法将返回棋盘上的cell个位置。但我收到一个错误,告诉我它是invalid return statement。你能解释一下我做错了吗?

         Board.prototype = {
            addCell: function(cell) {
                this.cells[getCellRepresentation(cell.x, cell.y)] = cell;
            }
            getCellAt: function(x,y) {
                return this.cells[getCellRepresentation(x,y)]
            }

        }

2 个答案:

答案 0 :(得分:4)

你缺少逗号。

Board.prototype = {
            addCell: function(cell) {
                this.cells[getCellRepresentation(cell.x, cell.y)] = cell;
            },
            getCellAt: function(x,y) {
                return this.cells[getCellRepresentation(x,y)]
            }

}

答案 1 :(得分:4)

我看到的第一件事就是你错过了一个逗号:

Board.prototype = {
        addCell: function(cell) {
            this.cells[getCellRepresentation(cell.x, cell.y)] = cell;
        },  // <---- put a comma here 
        getCellAt: function(x,y) {
            return this.cells[getCellRepresentation(x,y)]
        }

    }

您需要逗号的原因是2个函数是初始化语句的一部分,addCell和getCellAt都是Board.prototype的成员,并使用作为表达式列表成员的匿名函数表达式进行初始化。考虑JSON语法。

var obj = {
 name: "bob",
 age: 21,
 party: function() { ... }
}

如果函数是正常的命名函数,您可能会看到:

function addCell(cell) {

}

function getCellAt(x,y) {

}

不需要逗号,因为它们不是赋值语句,它们是单独的函数定义。

相关问题