2016-03-28 5 views
-1

ich den Code unten in eine ES2015 Klasse Refactoring bin (Ich habe eine ganze Reihe von Code verzichtet auf den Punkt zu halten):von Funktion Klasse in ES2015 Refactorying

//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) { 
    }; 

, die ich umgesetzt:

//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) { 
    ... 
    } 

} 

ich erhalte die folgenden Fehler:

Cannot read property 'scoring' of undefined at dealTableaus 

ich Typoskript Transpiler verwenden. Was könnte ich hier vermissen?

Antwort

0

Das sollte ein Syntaxfehler sein. Sie können keine function in der Mitte Ihres Klassenkörpers setzen.

Sie sollten es an der gleichen Stelle, wo es zuvor erklärt wurde: im Konstruktor. Gleiches gilt für die Zuweisung der newGame Methode (obwohl ich keinen Grund sehe, sie dort anzumelden).

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) { 
    } 
} 

Hinweis, dass scoring a (lokale) variabel ist, nicht eine Eigenschaft der Instanz, und nur in ihrem Umfang innerhalb der Konstruktionsfunktion, wo es als Parameter angegeben wird.