首页 > 解决方案 > 我正在用香草 JS 创建一个刽子手游戏,并且偶然发现了这个我无法弄清楚原因的错误

问题描述

我正在用香草 JS 创建一个刽子手游戏,并且偶然发现了这个我无法弄清楚原因的错误。

该错误表明“this.guessedLetters”在“getStatus 原型”中未定义。我真的不明白为什么会这样。

这是代码:

const Hangman = function (word, remainingGuesses) {
    this.word = word.toLowerCase().split('')
    this.remainingGuesses = remainingGuesses
    this.guessedLetters = []
    this.status = 'playing'
}

Hangman.prototype.getStatus = function () {
    let finished = true
    this.word.forEach(function(item){
        if(this.guessedLetters.includes(item))
        finished = false
    })
    if((this.remainingGuesses === 0 || this.remainingGuesses < 0) && finished === true ){
        this.status = 'failed'
    }
    else if(!finished){
        this.status = 'finished'
    }
    else{
        this.status = 'playing'
    }

    }




Hangman.prototype.getPuzzle = function () {
    let puzzle = ''

    this.word.forEach((letter) => {
        if (this.guessedLetters.includes(letter)) {
            puzzle += letter
        } else {
            puzzle += '*'
        }
    })

    return puzzle
}



Hangman.prototype.makeGuess = function (guess) {
    guess = guess.toLowerCase()
    const isUnique = !this.guessedLetters.includes(guess)
    const isBadGuess = !this.word.includes(guess)

    if (isUnique) {
        this.guessedLetters.push(guess)
    }

    if (isUnique && isBadGuess) {
        this.remainingGuesses--
    }
}

const game1 = new Hangman('Cat', 2)

console.log(game1.getPuzzle())
console.log(game1.remainingGuesses)

document.querySelector('#godzillaX').textContent = game1.getPuzzle()
document.querySelector('#godzillaY').textContent = game1.remainingGuesses

console.log(game1.status)

window.addEventListener('keypress', function (e) {
    const guess = e.key
    game1.makeGuess(guess)
    console.log(game1.getPuzzle())
    console.log(game1.remainingGuesses)
    document.querySelector('#godzillaX').textContent = game1.getPuzzle()
    document.querySelector('#godzillaY').textContent = game1.remainingGuesses
    game1.getStatus()
    console.log(game1.status)
})

标签: javascript

解决方案


这个错误是因为this指向function(item){而不是指向Hangman对象实例。

我看到两种可能的解决方案:

  1. 旧时尚风格:
Hangman.prototype.getStatus = function () {
    let finished = true
    const gl = this.guessedLetters
    this.word.forEach(function(item){
        if(gl.includes(item))
        finished = false
    })
  1. 使用胖箭头this将指向父级:
Hangman.prototype.getStatus = function () {
    let finished = true
    this.word.forEach(item => {
        if(this.guessedLetters.includes(item))
        finished = false
    })

推荐阅读