ES2015中从函数到类的重构

Refactoring from function to class in ES2015

本文关键字:重构 函数 ES2015      更新时间:2023-09-26

我正在将下面的代码重构为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是一个(局部)变量,而不是实例的属性,并且仅在构造函数内部的作用域中,在构造函数中它被声明为参数。