当多次使用方法时,跟踪类中的变量
Keep track of variables within class when using method multiple times
我有Ruby背景,所以尝试学习一些Javascript有点麻烦。我初始化一个名为Game
的类,并将玩家数量插入其中。我有一个这个类的方法叫做move
,它使玩家移动。我遇到的麻烦是,如果我在一行中进行多次移动,每次方法运行时变量都会重置。
对于move方法,我想要跟踪当前玩家的移动,同时也要跟踪所掷骰子的总数,而不管玩家是谁在移动。
你有什么见解吗?感谢所有的帮助!谢谢。
function Game(players) {
_players = createPlayers(players);
_total_dice = totalDice(players);
this.move = function(id, dice, value) {
current_player = _players[id - 1];
current_player = { id: current_player.id, dice_middle: dice, value: value, dice_left: current_player.dice_left - dice }
total_dice = _total_dice - dice;
}
}
function createPlayers(amount) {
var players = [];
var player_count = new Array(amount).join().split(',').map(function(item, index){ return ++index; })
for ( var i = 0; i < player_count.length; i++) {
player = { id: i + 1, dice_middle: 0, value: 0, dice_left: 5 }
players.push(player);
}
return players;
}
function totalDice(amount) {
total = amount * 5;
return total;
}
这就是我如何在Game
和移动。
var game = new Game(4);
game.move(1, 2, 3);
game.move(1, 1, 3);
每次移动,重新启动变量,所以在这个例子中,骰子总数保持在20,并且玩家的移动不会被"保存"。
函数只是函数,它们的行为不像类。尝试使用ES6类,应该可以做你想做的——下面的例子(未经测试):
class Game {
constructor(players) {
this._players = this.createPlayers(players);
this._total_dice = this.totalDice(players)
}
move (id, dice, value) {
current_player = this._players[id - 1];
current_player = { id: current_player.id, dice_middle: dice, value: value, dice_left: current_player.dice_left - dice }
total_dice = this._total_dice - dice;
}
createPlayers(amount) {
var players = [];
var player_count = new Array(amount).join().split(',').map(function(item, index){ return ++index; })
for ( var i = 0; i < player_count.length; i++) {
player = { id: i + 1, dice_middle: 0, value: 0, dice_left: 5 }
players.push(player);
}
return players;
}
totalDice(amount) {
total = amount * 5;
return total;
}
}
您已经编写了inside move函数
this.move = function(id, dice, value) {
total_dice = _total_dice - dice;
}
如果我假设正确,total_dice有一个错字,它应该是_total_dice。缺少"_"
相关文章:
- 敲除嵌套数组分页,如何跟踪变量或查找父记录
- 如何跟踪变量已更改的行's值
- 流星 在客户端跟踪服务器端变量
- 流星函数与变量跟踪
- JavaScript 跟踪全局变量
- 使用变量和谷歌跟踪代码管理器重写和重定向网址
- 跟踪服务器上的站点访问 - Meteor 中未定义的会话变量
- 您可以将自定义变量传递到Google Analytics事件跟踪中吗?
- 在Google Analytics.js事件跟踪发送中使用.Net变量
- 跟踪模板主干中的变量
- 会话变量递增/递减,js函数中的会话变量跟踪更新
- 当多次使用方法时,跟踪类中的变量
- 如何正确地将JavaScript变量插入自定义跟踪像素
- 如何从网站跟踪变量
- 变量跟踪点击
- 当在控制台中跟踪变量时,如何创建新行
- 跟踪变量实例
- 使用PHP echo传递跟踪变量
- 用javascript创建一个本地变量来跟踪日历上的月份
- 跟踪 C# 控制器和视图中的两个变量