function coordinate(x, y) {
    this.x = x,
    this.y = y
}

function generateBaracade(numBlocks) {
    var coordinate = getRandomBaracadeCoordinate();
    var xStyle = expandDirection.down;
    var yStyle = expandDirection.right;
    var xNumBlocks = findRandomFactor(numBlocks);
    var yNumBlocks = numBlocks / xNumBlocks;

    //figure out which way to expand the blocks
    if (coordinate.x + xNumBlocks > xBlocks) {
        xStyle = expandDirection.left;
    } else {
        xStyle = expandDirection.right;
    }

    if (coordinate.y + yNumBlocks > yBlocks) {
        yStyle = expandDirection.down;
    } else {
        yStyle = expandDirection.up;
    }

    for (var i = 0; i <= xNumBlocks - 1; i++) {
        for (var j = 0; j <= yNumBlocks - 1; j++) {
            var tempBlock = Object.create(block);
            tempBlock.type = "obstruction";
            tempBlock.color = "grey";
            tempBlock.illegalTerrain = true;
            tempBlock.coordinate = new coordinate(coordinate.x + (i * xStyle), coordinate.y + (j * yStyle));
            blockContainer[coordinate.x + (i * xStyle)][coordinate.y + (j * yStyle)] = tempBlock;
        };
    };
}


我在行上收到“未捕获的TypeError:对象不是函数”:

tempBlock.coordinate = new coordinate(coordinate.x + (i * xStyle), coordinate.y + (j * yStyle));


这很奇怪,因为我遵循mozilla指南进行操作:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

编辑:getRandomBaracadeCoordinate的源。 return语句正是我想要做的,并且执行时没有错误。

function getRandomBaracadeCoordinate() {
    var x = Math.floor((Math.random() * (xBlocks)));
    var y = Math.floor((Math.random() * (yBlocks)));
    return new coordinate(x, y);
}

最佳答案

您通过在coordinate的第一行上使用其他相同的名称来掩盖getBaracade函数:

var coordinate = getRandomBaracadeCoordinate();


getRandomBaracadeCoordinate()返回的内容都不是函数,因此new coordinate会引发错误。

10-05 22:54
查看更多