javascript - 我正在用香草 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)
})
解决方案
这个错误是因为this
指向function(item){
而不是指向Hangman
对象实例。
我看到两种可能的解决方案:
- 旧时尚风格:
Hangman.prototype.getStatus = function () {
let finished = true
const gl = this.guessedLetters
this.word.forEach(function(item){
if(gl.includes(item))
finished = false
})
- 使用胖箭头
this
将指向父级:
Hangman.prototype.getStatus = function () {
let finished = true
this.word.forEach(item => {
if(this.guessedLetters.includes(item))
finished = false
})
推荐阅读
- java - Apache Poi - 用逗号分隔数字的 Excel 单元格转换为十进制数
- spring-boot - 来自 application.yml 的 ObjectMapper 配置未在测试中使用
- javascript - AJAX - 根据间隔进行 API 调用
- sql-server - 如何从sql中的特殊字符中找到第二个字符
- php - 使用 PHP 库进行 FFMPEG 音频合并
- ios - 在 Firestore 中保存数组并在 Swift 的 uitableview 中显示它
- python - 用于 Intel Hex 的 8 位行校验和计算器
- angular - 如何使用 Angular 9 和 NGRX 在子组件中获取数据?
- python - 我想提取 h4 中的文本以及与 h4 相关的文本以及与它们相关的链接(使用 xpath)
- php - 根据 Apache 日志文件,Wordpress 出现黑客攻击(后门 PHP 特洛伊木马)和服务器被用作对抗他人的机器人