Javascript:如何在构造函数中的空变量中存储变量
在startGamemethod中,我试图将getrandomPhase方法中选定的短语存储到null属性。它总是给我一个错误,说 Game.activePhrase为空 我做错了什么 Game.js:Javascript:如何在构造函数中的空变量中存储变量,javascript,constructor,Javascript,Constructor,在startGamemethod中,我试图将getrandomPhase方法中选定的短语存储到null属性。它总是给我一个错误,说 Game.activePhrase为空 我做错了什么 Game.js: class Game { constructor() { this.missed = 0; //directly put the phrases in the constructor this.phrases = [new Phrase("hello world")
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}`);
您从未将.activePhrase分配给您试图调用的.activePhrase,就好像它是一个函数,但它不是。请尝试将PHR分配给此.ActivePhase:
在从StartName方法返回activePhase变量之前,为其赋值
this.activePhrase = phrs;
像
this.activePhrase不是function-因此this.activephrasephs不会做任何事情。只需分配值:
this.activePhrase = phrs;
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;
}
this.activePhrase = phrs;