我正在将下面的代码重构为一个ES2015类(为了坚持这一点,我省略了一整串代码):
//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) {
};我把它改为:
//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) {
//...
}
}我收到以下错误:
Cannot read property 'scoring' of undefined at dealTableaus我使用的是TypeScript转播器。我在这里会错过什么?
发布于 2016-03-28 15:48:35
这应该是语法错误。您不能将function放在类主体的中间。
您应该将它放在前面声明的位置:构造函数中。newGame方法的赋值也是如此(虽然我不认为有任何理由将它放在首位)。
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) {
}
}请注意,scoring是一个(局部变量)变量,而不是实例的属性,并且仅在构造函数函数的作用域中声明为参数。
https://stackoverflow.com/questions/36265440
复制相似问题