我想从图块的节点列表中写下我在棋盘(跳棋)上的图形位置。我定义了一个二维数组并用 0 填充它。如果我在方法开始处使用
this._matrix[0][1] = 1;
,我可以自由更改该值。但是,当在 forEach 数组内更改它时,我收到此类错误。
我的代码:
class Game{
_matrix = Array(8).fill().map(() => Array(8).fill(0));
_board = document.querySelectorAll("div.container>div"); // all tiles
constructor(blackTiles){
this.blackTiles = blackTiles;
}
fillMatrix(){
console.log(this._matrix[0][1]) // 0
this._matrix[0][1] = 1 // no errors
console.log(this._matrix[0][1]) // 1
this._board.forEach(function(element, i){
if(i < 8){
if(element.classList.contains("infest")){ //tiles, that have figures, have class "infest"
try{
let row = i / 8;
let col = i % 8;
this._matrix[parseInt(row)][parseInt(col)] = 1; //error
} catch(Error) { console.error(Error); }
}
i++;
}
});
return this._matrix;
}
}
完整错误:
TypeError: Cannot read properties of undefined (reading '_matrix')
at script.js:41:30
at NodeList.forEach (<anonymous>)
at Game.fillMatrix (script.js:35:21)
at window.onload (script.js:102:22)
正如您正确发现的那样,问题出在该特定行上。
这是因为在函数内部(用
function(){}
定义),this
指的是函数本身,而不是包含的上下文。
此时您有三个选择。
this
的引用:const _this = this;
list.forEach(function(){
_this.something;
})
list.forEach((function(){
this.something;
}).bind(this));
list.forEach(() => {
this.something;
});
_handleSomething = () => {
this.something;
}
list.forEach(this._handleSomething);
```js