首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ES2015中从函数重构到类

在ES2015中从函数重构到类
EN

Stack Overflow用户
提问于 2016-03-28 15:27:19
回答 1查看 63关注 0票数 0

我正在将下面的代码重构为一个ES2015类(为了坚持这一点,我省略了一整串代码):

代码语言:javascript
复制
//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) {
    };

我把它改为:

代码语言:javascript
复制
//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) {
    //...
  }

}

我收到以下错误:

代码语言:javascript
复制
 Cannot read property 'scoring' of undefined at dealTableaus

我使用的是TypeScript转播器。我在这里会错过什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-28 15:48:35

这应该是语法错误。您不能将function放在类主体的中间。

您应该将它放在前面声明的位置:构造函数中。newGame方法的赋值也是如此(虽然我不认为有任何理由将它放在首位)。

代码语言:javascript
复制
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是一个(局部变量)变量,而不是实例的属性,并且仅在构造函数函数的作用域中声明为参数。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36265440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档