Javascript 未捕获类型错误:在JS中,this.changeRoundScore不是htmlButtoneElement.roll(app.JS:35)的函数
我对JS比较陌生,在尝试编写一个简单的“猪游戏”时遇到了一个错误。我尝试了很多事情,但我还没有弄清楚到底发生了什么 如果我掷骰子Javascript 未捕获类型错误:在JS中,this.changeRoundScore不是htmlButtoneElement.roll(app.JS:35)的函数,javascript,Javascript,我对JS比较陌生,在尝试编写一个简单的“猪游戏”时遇到了一个错误。我尝试了很多事情,但我还没有弄清楚到底发生了什么 如果我掷骰子dice.roll()在我的JS文件中没有错误。只有当我点击Chrome上的按钮时,addEventListener才会出错 这就是我得到的错误: 未捕获类型错误:this.changeRoundScore不是htmlButtoneElement.roll(app.js:35)中的函数 编辑:我刚刚将启动功能更改为以下功能,它工作了……有人能解释一下原因吗 let st
dice.roll()代码>在我的JS文件中没有错误。只有当我点击Chrome上的按钮时,addEventListener才会出错
这就是我得到的错误:
未捕获类型错误:this.changeRoundScore不是htmlButtoneElement.roll(app.js:35)中的函数
编辑:我刚刚将启动
功能更改为以下功能,它工作了……有人能解释一下原因吗
let start = function() {
console.log(playerOne);
console.log(playerTwo);
console.log(dice);
document.querySelector('.btn-roll').addEventListener('click', function() {
dice.roll();
});
}
原始代码:
class Player {
constructor(active) {
this.score = 0;
this.roundScore = [];
this.active = active;
}
changeActive(active) {
this.active = active;
}
addRoundScore(score) {
this.roundScore.push(score);
}
}
class Dice {
constructor(playerOne, playerTwo) {
document.querySelector('.dice').style.display = 'none';
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
roll() {
let roll = Math.floor(Math.random()*6) + 1;
// document.querySelector('.dice').style.display = 'visible';
this.changeRoundScore(roll);
}
changeRoundScore(score) {
document.querySelector('#current-' + activePlayer).textContent = score;
document.querySelector('.dice').src = 'dice-' + score + '.png';
if (activePlayer === 0) {
playerOne.addRoundScore(score);
} else if (activePlayer === 1) {
playerTwo.addRoundScore(score);
}
}
}
let activePlayer = 0;
let playerOne = new Player(1);
let playerTwo = new Player(0);
let dice = new Dice(playerOne, playerTwo);
let start = function() {
console.log(playerOne);
console.log(playerTwo);
console.log(dice);
document.querySelector('.btn-roll').addEventListener('click', dice.roll);
}
start();