'Refactoring from function to class in ES2015
I am refactoring the code below into a ES2015 class (I have omitted a whole bunch of code to stick to the point):
//game.js
angular.module("klondike.game", [])
.service("klondikeGame", ["scoring", KlondikeGame]);
function KlondikeGame(scoring) {
this.newGame = function newGame() {
var cards = new Deck().shuffled();
this.newGameFromDeck(cards);
};
function dealTableaus(cards) {
var tableaus = [
new TableauPile(cards.slice(0, 1), scoring),
];
return tableaus;
}
}
KlondikeGame.prototype.tryMoveTopCardToAnyFoundation = function (sourcePile) {
};
Which I converted to :
//game.js
class KlondikeGame {
constructor(scoring) {
this.scoring = scoring;
}
newGame() {
var cards = new Deck().shuffled();
this.newGameFromDeck(cards);
}
function dealTableaus(cards) {
var tableaus = [
new TableauPile(cards.slice(0, 1), this.scoring), //<-- this throws an error
];
return tableaus;
}
tryMoveTopCardToAnyFoundation(sourcePile) {
//...
}
}
I receive the following error :
Cannot read property 'scoring' of undefined at dealTableaus
I am using a TypeScript transpiler. What could I be missing here?
Solution 1:[1]
That should be a syntax error. You cannot put a function in the middle of your class body.
You should put it in the same place where it was declared previously: in the constructor. Same goes for the assignment of the newGame method (though I don't see any reason to put it there in the first place).
export class KlondikeGame {
constructor(scoring) {
this.newGame = function newGame() {
var cards = new Deck().shuffled();
this.newGameFromDeck(cards);
};
function dealTableaus(cards) {
var tableaus = [new TableauPile(cards.slice(0, 1), scoring)];
return tableaus;
}
}
tryMoveTopCardToAnyFoundation(sourcePile) {
}
}
Notice that scoring is a (local) variable, not a property of the instance, and only in scope inside the constructor function where it is declared as a parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bergi |
