javascript class 从另一个方法内部调用方法,导致 "moveToCell is not a function" 错误

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

我有这个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);
            //}
        }
    }
}

每当我在函数 runTask() 中调用 moveToCell() 函数时,我都会收到一条错误消息,指出“moveToCell”函数未定义,因此,我无法更新对象在地图中的位置.

我也试过 this.moveToCell() insted,但结果是同样的问题。我不明白这里有什么问题。

任何人都可以 post 对此有什么想法吗?提前致谢

因为在class里面,所以需要用到this运算符。将其更改为:

this.moveToCell(this.x, y);

当您在 setTimeout(function () { ... }) 中使用它时,您需要缓存 this:

this.x += 1;
_this = this;
setTimeout(function() {
    _this.moveToCell(this.x, y);
}, 800);

您需要指定调用方法的实例,应该是this

此外,this 不会保存在正常的闭包中。使用箭头函数来保持上下文。

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