Search code examples
javascriptfunctionclassruntime-error

javascript class method call from inside another method, results in "moveToCell is not a function" error


I have this class:

class AGV {
    constructor(id, x, y, agvcolor, matrixTable) {
        this.id = id;
        this.x = x;
        this.y = y;
        this.color = agvcolor;
        this.xOffset = 1;
        this.yOffset = 1;
        this.matrix = matrixTable;
    }
    setX(newX) {
        this.x = newX;
    }
    setY(newY) {
        this.y = newY;
    }
    lastCoordinates() {
        return JSON.stringify({
            'x': this.x,
            'y': this.y
        });
    }
    spawn() {
        var xCoord = this.x - this.xOffset;
        var yCoord = this.y - this.yOffset;
        var cell = this.matrix.childNodes[1].children[yCoord].children[xCoord];
        cell.style.background = this.color;
        cell.innerHTML = this.id;
    }
    moveToCell(x, y) {
        console.log("rolling to x: " + x + " y: " + y);
        this.clearPreviousCell(this.x, this.y);
        // offsets are needed to convert array index to actual position
        var xCoord = x - xOffset;
        var yCoord = y - yOffset;
        var cell = this.matrix.childNodes[1].children[yCoord].children[xCoord];
        cell.style.background = this.color;
        cell.innerHTML = this.id;
    }
    clearPreviousCell(x, y) {
        var xCoord = x - xOffset;
        var yCoord = y - yOffset;
        var cell = this.matrix.childNodes[1].children[yCoord].children[xCoord];
        cell.style.background = "#fff";
        cell.innerHTML = "";
    }
    runTask(x, y, z) {
        console.log("Running task. Target: X: " + x + " Y: " + y);
        if (this.x < x) {
            //while (this.x < x) {
            this.x += 1;
            setTimeout(function() {
                moveToCell(this.x, y);
            }, 800);
            //}
        }
    }
}

And whenever I call moveToCell() function inside function runTask(), I get an error stating that the "moveToCell" function is not defined and as so, I cannot update the object's position in the map.

I've also tried this.moveToCell() insted, but results in the same problem. I don't understand what is wrong here.

Can anyone please post any thoughts on this? Thanks in advance


Solution

  • You need to specify the instance to call the method on, which should be this.

    Also, this is not saved in normal closures. Use an arrow function to keep the context.

        runTask(x, y, z) {
            console.log("Running task. Target: X: " + x + " Y: " + y);
            if (this.x < x) {
                //while (this.x < x) {
                this.x += 1;
                setTimeout(() => this.moveToCell(this.x, y), 800);
                //}
            }
        }