Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获类型错误:在JS中,this.changeRoundScore不是htmlButtoneElement.roll(app.JS:35)的函数_Javascript - Fatal编程技术网

Javascript 未捕获类型错误:在JS中,this.changeRoundScore不是htmlButtoneElement.roll(app.JS:35)的函数

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

我对JS比较陌生,在尝试编写一个简单的“猪游戏”时遇到了一个错误。我尝试了很多事情,但我还没有弄清楚到底发生了什么

如果我掷骰子
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();