[英]Javascript use anonymous function inside class methods
我正在将工作代码重构为class
。 我在加载一些Json
并对其进行解析时遇到错误。 此代码可以作为function
正常工作,但不能在class
method
内工作。
代码:
class MemoryCards {
constructor() {
this.gameData = [];
this.cardData = [];
this.currentLives = 0;
this.levelLives = 0;
this.level = 1;
this.hasFlippedCard = false;
this.lockDeck = false;
this.firstCard, this.secondCard;
this.trackMatches = 0;
this.cardSelection = [];
}
startGame () {
this.loadJSON(function(response) {
this.gameData = JSON.parse(response);},
'gameData.json');
}
loadJSON(callback, file) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', `assets/data/${file}`, false);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
}
错误:
game.js:21 Uncaught TypeError: Cannot set property 'gameData' of undefined
at game.js:21
at XMLHttpRequest.xobj.onreadystatechange (game.js:68)
at MemoryCards.loadJSON (game.js:71)
at MemoryCards.startGame (game.js:20)
at (index):77
实施箭头 Function :
startGame () {
this.loadJSON((response) => {
this.gameData = JSON.parse(response);
}, 'gameData.json');
}
为什么它有效?
这是因为this关键字。 this关键字默认是指全局 Object 。 函数有自己的块 scope 但是箭头和普通函数在寻找全局 object时有不同的世界。
此代码或普通 function正在寻找它的父 object ,即startGame function。
function(response) {
this.gameData = JSON.parse(response);
}, 'gameData.json')
但是这个箭头 function正在寻找最后一个父 object ,那就是MemoryCards
(response) => {
this.gameData = JSON.parse(response);
}, 'gameData.json')
这样想箭头 function正在寻找LAST scope 或{ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.