只是想学习ES6课程并试图找出我遇到的这个问题。我有一个名为claim
的方法,我需要使用另一种方法来计算被称为probability
的东西的概率,它们都有两个参数。我得到了`概率没有定义。我使用课程做错了什么?我是否需要在构造函数中定义它?
错误消息
ReferenceError: probability is not defined
代码
class Game {
constructor(players) {
this._players = this.createPlayers(players);
this._total_dice = this.totalDice(players);
}
move (id, dice, value) {
var current_player = this._players[id - 1];
this._players[id - 1] = { id: current_player.id, dice_middle: dice, value: value, dice_left: current_player.dice_left - dice };
this._total_dice = this._total_dice - dice;
console.log([this._total_dice, this._players[id - 1]])
}
claim (dice, value) {
var result = (probability(this._total_dice, this._total_dice) + probability(this._total_dice - 1.0, this._total_dice)) * 100
console.log(result);
}
factorial(n) {
if (n < 0) { return -1; } else if (n == 0) { return 1; }
var number = n;
while (number-- > 2) { number *= n; } return number;
}
probability(n, k) {
if (k <= n) {
return (this.factorial(n) / (this.factorial(k) * this.factorial(n - k))) * Math.pow(1.0/6.0, k) * Math.pow(5.0/6.0, n-k);
} else {
return 0.0;
}
}
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++) {
var player = { id: i + 1, dice_middle: 0, value: 0, dice_left: 5 }
players.push(player);
}
return players;
}
totalDice(amount) {
var total = amount * 5;
return total;
}
}
var game = new Game(4);
game.move(1, 2, 3);
game.move(1, 1, 3);
game.claim(2,3);
您将看到概率也使用因子方法来计算参数的阶乘。我假设问题是什么,我可以对两者都应用修复,因此可以解决或至少定义声明方法和概率方法。请注意,我使移动方法正常工作,但它不需要任何其他方法来工作。
任何帮助将不胜感激!谢谢!
答案 0 :(得分:3)
由于probability
是class Game
上的实例方法,您需要使用this.
引用它,就像您对其他方法所做的那样:
claim (dice, value) {
var result = (this.probability(this._total_dice, this._total_dice) + this.probability(this._total_dice - 1.0, this._total_dice)) * 100
^^^ ^^^
console.log(result);
}
正如所写的那样,您的代码正在寻找一种名为probability
的方法,该方法更进一步。