gpt4 book ai didi

Javascript:如何将变量存储在构造函数中的空变量中

转载 作者:行者123 更新时间:2023-12-03 00:01:49 25 4
gpt4 key购买 nike

startGame() 方法中,我尝试将 getRandomPhrase() 方法中选定的短语存储到 null 属性。它一直向我抛出一个错误,说

Game.activePhrase is null

我做错了什么?

游戏.js:

class Game {

constructor() {
this.missed = 0;
//directly put the phrases in the constructor
this.phrases = [new Phrase("hello world"),
new Phrase("Wolf on wall street"),
new Phrase("Despite making"),
new Phrase("Karen took the kids"),
new Phrase("alright about to head out")
];
this.activePhrase = null;
}

getRandomPhrase() {
//returns 5 of the random phrases
return this.phrases[Math.floor(Math.random() * this.phrases.length)];
}

startGame() {
let hid = document.getElementById('overlay');
hid.style.display = "none";
let phrs = this.getRandomPhrase();
phrs.addPhraseToDisplay();
return this.activePhrase(phrs); //trying to store it by doing this
}
}

App.js

const game = new Game();
game.startGame();
console.log(`Active Phrase - phrase: ${game.activePhrase.phrase}`);

最佳答案

在从 startGame 方法返回之前为 activePhase 变量赋值

this.activePhrase = phrs;

喜欢

  startGame() {
let hid = document.getElementById('overlay');
hid.style.display = "none";
let phrs = this.getRandomPhrase();
phrs.addPhraseToDisplay();
this.activePhrase = phrs; //Key to fix your issue
return this.activePhrase;
}

关于Javascript:如何将变量存储在构造函数中的空变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55136087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com