I am refactoring working code in to class
. I am getting an error where I am loading some Json
and parsing it. This code works fine as a function
but not inside a class
method
.
Code:
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);
}
}
Error:
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