我有這堂課:
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);
//}
}
}
}
每當我moveToCell()在 function 中呼叫 function時runTask(),都會收到一條錯誤訊息,指出未定義“moveToCell”函式,因此,我無法更新物件在地圖中的位置。
我也嘗試過this.moveToCell()insted,但會導致同樣的問題。我不明白這里有什么問題。
任何人都可以對此發表任何想法嗎?提前致謝
uj5u.com熱心網友回復:
您需要指定要呼叫該方法的實體,它應該是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);
//}
}
}
uj5u.com熱心網友回復:
由于它在類內部,因此您需要使用this運算子。將其更改為:
this.moveToCell(this.x, y);
當您在其中使用它時setTimeout(function () { ... }),您需要快取this:
this.x = 1;
_this = this;
setTimeout(function() {
_this.moveToCell(this.x, y);
}, 800);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479309.html
標籤:javascript 功能 班级 运行时错误
上一篇:如何將圖表轉換為Java代碼?
