我最初把我的游戏和关键对象暴露为全局变量。我决定做一个闭包,所以我可以隐藏win键,只在需要时公开数据。
我不确定如何正确获取/设置值。我想我需要定义到对象的路由,但我想的方式是为我需要访问的每个属性创建一个get / set函数,我发现这非常难看。你可以在我试图制作的setStatus()中看到这一点。
我的JavaScript目前有点基础,所以如果你对改进代码有什么建议,请告诉我!
更新代码 对于我的setStatus,我希望能够让这一个函数更新相应的键:status in value,但我不确定如何优雅地执行它。目前我将其作为检查" moveNumber"的字符串值。或" movePool"。如果我这样做,那么当我创建一个setPlayers函数时,我必须检查p1 / p2并检查密钥。应该有更好的方法。
var data = (function() {
var game = {
status: {
"moveNumber": 1,
"movePool": []
},
players: {
p1: {
"title": "Player 1",
"moves": [],
"marker": "#17C000"
},
p2: {
"title": "Player 2",
"moves": [],
"marker": "#E60000"
}
}
};
var key = {
win: {
"winSet": ["abc","def","ghi","adg","beh","cfi","aei","gec"]
},
};
return {
getGame: function() {
return game.players;
},
getStatus: function() {
return game.status;
},
getWin: function() {
return key.win;
},
setStatus: function(route, val) {
if (route === "moveNumber") {
game.status.moveNumber = val;
}
else if (route === "movePool") {
game.status.movePool = val;
}
}
}
})();
原始代码发布
var data = (function() {
var game = {
players: {
status: {
"moveNumber": 1,
"movePool": []
},
p1: {
"title": "Player 1",
"moves": [],
"marker": "#17C000"
},
p2: {
"title": "Player 2",
"moves": [],
"marker": "#E60000"
}
}
};
var key = {
win: {
"winSet": ["abc","def","ghi","adg","beh","cfi","aei","gec"]
},
};
return {
getGame: function() {
return game.players;
},
getWin: function() {
return key.win;
},
setStatus: function(route, val) {
if (route == status) {
return this.game.players.status
}
}
};
})();