Я хочу создать фабрику, которая отвечает за создание PlayerList, но у меня возникают проблемы с доступом к переменным, установленным в функции initialize. Код
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);
});
Я хочу обратиться к массиву игроков внутри методов добавления и удаления, но я возвращаюсь к неопределенным.
Здесь 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);
});
var playerList = (function() {
var playerLists = {};
playerList.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 playerLists;
})();
app.factory( "PlayerList", playerList.playerList);