我有一个'渲染'功能:
render: function(playerId){
this.getTotalPoints(playerId);
// and some other code after this;
}
这个'渲染'可以在有或没有playerId的情况下执行函数。这是getTotalPoints函数:
getTotalPoints: function(playerId){
if(playerId){
this.allplayers[playerId].totalPoints = this.calculatePoints(this.allplayers[playerId].cards);
}else{
this.allplayers.forEach(function(element, index){
element.totalPoints = this.calculatePoints(element.cards);
}.bind(this));
}
}
实际计算点数的第三个函数
calculatePoints: function(cards){
points = 0;
for( var i = 0; i < cards.length; i++){
points+=cards[i].points;
};
return points;
}
我在getTotalPoints
重复自己,在那里我打电话给this.calculatePoints
- 一个用于一个玩家,然后一个用于所有玩家,具体取决于playerId
是否设置或不。
我有可能避免这种情况并简化代码吗?
答案 0 :(得分:0)
我看到两个不同的功能:calculatePointsForPlayer
和calculatePointsForPlayers
。第二个函数将调用第一个函数。
答案 1 :(得分:0)
我会做类似的事情:
getTotalPoints: function(playerId){
var selected = playerId ? [this.allplayers[playerId]] : this.allplayers;
selected.forEach(function(element, index){
element.totalPoints = this.calculatePoints(element.cards);
}.bind(this));
}
但是,由于你更改了玩家的状态,我不会调用函数getTotalPoints
,也许computeTotalPoints
?