我已经开始编写一些代码来实现JavaScript中的简单游戏。其基本思想是,dealer.game拥有一系列保持游戏当前状态的对象(玩家,手,资金等)。然后我有各种方法来操纵这些对象。我选择使用原型链,因为可能有多个dealer.game实例实例,所以我想在这些实例之间共享方法。
工作小提琴:
和代码:
dealer = {}
dealer.game = function() {
this.player = {};
this.hand = {};
this.set = {};
this.funds = {};
this._drawBoard();
};
dealer.game.prototype._drawBoard = function() {
//draw board in svg here
};
dealer.game.prototype.addPlayer = function(name,funds) {
this.setFunds(name,funds);
this._drawPlayer(name);
};
dealer.game.prototype._drawPlayer = function(name) {
this.player[name] = '';
};
dealer.game.prototype._getPlayer = function(name) {
this.player[name] = '';
};
dealer.game.prototype.setFunds = function(name,funds) {
this.funds[name] = funds;
};
dealer.game.prototype.removeFunds = function() {
};
dealer.game.prototype.drawFunds = function() {
};
var poker = new dealer.game();
poker.addPlayer("jenny",200);
poker.addPlayer("jack",100);
console.log(poker.player);
console.log(poker.funds);
我直接看到的问题是即使是这个最小的代码样板,通过原型链向对象添加方法也会变得混乱。我有一堆方法可以对玩家做些什么,然后更多的东西给玩家筹集资金......随着这种情况的增长,我可以看到我最终将会有大量的方法直接关联到原型链在它们的作用方面都是混合的。我知道技术上没有任何问题,但有没有更好的方法来组织这个?我考虑了需要实例化的单独对象......类似于:
dealer.funds = function() {
};
dealer.funds.prototype.addFunds = function() {
};
但问题在于,实例化的资金对象将无法再访问核心播放器,手,设置或资助player.game中包含的对象。
我如何重组这个?
答案 0 :(得分:0)
答案是盯着我的脸。为我的应用程序的不同部分创建单独的类:
dealer = {};
dealer.game = function() {
this.player = {};
};
dealer.game.prototype.addPlayer = function(name,funds) {
//assign the object returned by dealer.player to my game.player object
//this way my application always has access to all players that have been created
this.player[name] = new dealer.player();
};
dealer.player = function() {
//do some stuff and then return the object
return this;
};