我已经开始编写一些代码来用 JavaScript 实现一个简单的游戏。基本思想是 dealer.game 包含一堆对象(玩家、手牌、资金等),这些对象包含游戏的当前状态。然后我有各种方法来操纵这些对象。我选择使用原型(prototype)链,因为 dealer.game 实例可能有多个实例,所以我希望在这些实例之间共享方法。
工作 fiddle :
和代码:
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);
我立即看到的问题是,即使是这种通过原型(prototype)链向对象添加方法的最小代码样板也会变得困惑。我有很多方法可以对玩家做一些事情,然后更多的方法可以对资金做一些事情......随着它的发展,我可以看到我最终会得到大量直接与原型(prototype)链,它们在功能上都是混合的。我知道这在技术上没有任何问题,但是有没有更好的方法来组织它?我考虑了需要实例化的单独对象......类似于:
dealer.funds = function() {
};
dealer.funds.prototype.addFunds = function() {
};
但这样做的问题是实例化的资金对象将无法再访问包含在 player.game 中的核心玩家、手牌、套装或资金对象。
我该如何重组它?
最佳答案
答案就在眼前。为我的应用程序的不同部分创建单独的类:
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;
};
关于javascript - 重组了很多建立在原型(prototype)链上的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19707066/