Nick H
Nick H

Reputation: 2035

Uncaught TypeError: object is not a function on object creation

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

I get the 'Uncaught TypeError: object is not a function' on the line:

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

This is strange as I am following the mozilla guide to doing this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

EDIT: Source for getRandomBaracadeCoordinate. The return statement is exactly what I want to do, and executes without error.

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

Upvotes: 0

Views: 51

Answers (2)

Jordan Running
Jordan Running

Reputation: 106027

You are shadowing the coordinate function by giving something else the same name on the first line of getBaracade:

var coordinate = getRandomBaracadeCoordinate();

Whatever getRandomBaracadeCoordinate() returns isn't a function, so new coordinate throws an error.

Upvotes: 1

zlumer
zlumer

Reputation: 7004

coordinate is an object containing { x, y } and initialized here:

var coordinate = getRandomBaracadeCoordinate();

 

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

Probably you mistyped new coordinate() instead of new Coordinate() (if Coordinate is a class).

You should look at the source of getRandomBaracadeCoordinate() — if it returns an object of some class, you should create an instance of this class. Otherwise, if it returns a simple { x:50, y:15 } object, you can create it inline:

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

Upvotes: 0

Related Questions