未捕获的TypeError:对象不是对象创建的函数

时间:2015-06-07 22:40:57

标签: javascript

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);
}

2 个答案:

答案 0 :(得分:1)

您通过在coordinate的第一行提供其他名称相同的内容来隐藏getBaracade函数:

var coordinate = getRandomBaracadeCoordinate();

无论getRandomBaracadeCoordinate()返回什么都不是函数,因此new coordinate会抛出错误。

答案 1 :(得分:0)

coordinate是一个包含{ x, y }并在此处初始化的对象:

var coordinate = getRandomBaracadeCoordinate();

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

可能您错误输入new coordinate()而不是new Coordinate()(如果Coordinate是一个类)。

你应该查看getRandomBaracadeCoordinate()的来源 - 如果它返回某个类的对象,你应该创建这个类的实例。否则,如果它返回一个简单的{ x:50, y:15 }对象,则可以内联创建它:

tempBlock.coordinate = { x: coordinate.x + (i * xStyle), y: coordinate.y + (j * yStyle) };
相关问题