2013-10-31 29 views
2

我已經開始編寫一些代碼來實現JavaScript中的簡單遊戲。基本的想法是,經銷商擁有一堆保持當前遊戲狀態的對象(玩家,手牌,資金等)。然後我有各種方法來操縱這些對象。我選擇使用原型鏈,因爲可能有多個dealer.game實例的實例,所以我想要在這些實例之間共享方法。重組構建在原型鏈上的很多方法

工作小提琴:

http://jsfiddle.net/BhPrQ/

,代碼:

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() { 

}; 

但這樣做的問題是,實例化對象的資金將不再有機會獲得核心球員,另一方面,設置或資金對象包含播放器中。遊戲。

如何重新組織這個?

回答

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; 
};