2015-11-03 82 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);