2015-11-03 83 views
0

我想創建一個負責生成PlayerList的工廠,但是我在訪問我在初始化函數中設置的變量時遇到問題。代碼是參考在角度工廠中初始化變量

app.factory("PlayerList", function(){ 

    // Define the PlayerList function 
    var PlayerList = function() { 

     this.initialize = function() { 
      // create an array for our players 
      var players = []; 
     }; 

     this.add = function(player) { 
      this.players.push(player); 
     } 

     this.remove = function(player) { 
      if (players.length > 0) 
      { 
       this.players.splice(players.indexOf(player), 1);  
      } 
     } 

     this.initialize(); 
    }; 

    return (PlayerList); 

}); 

我想參考播放器數組裏面的添加和刪除方法,但我回來了未定義。

回答

0

這裏var players = [];是局部變量initialize但你的期待this.players.push(player);意味着players應該在PlayerList範圍。

所以,你的工廠應該像

app.factory("PlayerList", function() { 

    // Define the PlayerList function 
    var PlayerList = function() { 

     var self = this; 

     this.players = []; 

     this.initialize = function() { 
      self.players = []; 
     }; 

     this.add = function (player) { 
      self.players.push(player); 
      console.log(self.players); 
     } 

     this.remove = function (player) { 
      if (self.players.length > 0) { 
       self.players.splice(self.players.indexOf(player), 1); 
      } 
     } 

     this.initialize(); 
    }; 

    return (PlayerList); 
}); 
0

VAR playerList =(函數(){

變種playerLists = {};

playerList.playerList =函數(){

this.initialize = function() { 
     // create an array for our players 
     var players = []; 
    }; 

    this.add = function(player) { 
     this.players.push(player); 
    } 

    this.remove = function(player) { 
     if (players.length > 0) 
     { 
      this.players.splice(players.indexOf(player), 1);  
     } 
    } 

    this.initialize(); 
}; 

return playerLists; 

})();

app.factory( 「PlayerList」,playerList.playerList);