ES2015中从函数到类的重构
Refactoring from function to class in ES2015
我正在将下面的代码重构为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转发器。我在这里会错过什么?
这应该是一个语法错误。不能将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
是一个(局部)变量,而不是实例的属性,并且仅在构造函数内部的作用域中,在构造函数中它被声明为参数。
相关文章:
- jQuery:重构为函数
- 重构查找函数
- 将ECMAScript 6析构函数赋值(ES2015)重构为旧版本的javascript
- Javascript重构通常称为函数
- 将多个jQuery点击函数重构为一个函数
- 渲染重构会导致未定义的函数
- 如何将.show()更改为.thoggle()而不复制函数中的项(如何重构)
- ES2015中从函数到类的重构
- Javascript:重构循环之外的函数
- 重构作为属性从 es5 传递到 es6 的函数
- 将 PHP 函数的 3 小位重构为 JS - 数组,如果为空且匹配 url
- 重构以避免 setTimeout 函数
- 重构JavaScript原型构造函数中的重复代码
- 重构 Jquery 函数以使其可重用
- 重构C函数以查找O(n)中二进制树的直径到JavaScript
- 如何使用Chai/Sinon重构jasmine.any()函数
- jQuery重构了函数
- 为什么可以't我在封闭函数之外重构这个匿名函数
- 如何进行重构"提取函数“;在Javascript中
- 重构 JavaScript 函数