[英]Javascript: uncaught typeerror undefined is not a function for object methods
我做一個簡單的問答游戲。 這是我在一個對象中擁有的一些relevan方法。
但是不起作用。 我總是在'rightAnswerGot'函數中出現錯誤。 控制台為this.addVariantsHtml(this.updateCharacter())丟棄“未定義的未捕獲類型錯誤不是對象方法的功能”;
BasicGame.Game.prototype = {
actionOnClick: function (button) {
var log;
if(button.value==this.char_bubble.text) {
setTimeout(this.rightAnswerGot,1000);
} else {
// wrong
swoshsound.play();
}
console.log(log);
},
rightAnswerGot: function (){
this.addVariantsHtml(this.updateCharacter());
},
addVariantsHtml: function(id) {
this.answer = this.getAnswersVariants(id);
for (var i = 0; i < 6; i++) {
this.button[i].value = this.answer[i]['trans'];
this.button[i].char_id = this.answer[i]['id'];
this.ans_text[i].setText(this.answer[i]['trans']);
}
},
updateCharacter: function() {
var i = this.getRandomCharacter();
console.log("updateCharacter: "+i + " " +this.chars[i]);
this.char_bubble.setText(this.chars[i].getPath());
return i;
}
}
目的是在用戶選擇正確答案時凍結游戲一秒鍾,然后轉到下一個問題。 任何想法為什么會發生?
謝謝
在我看來,這是經典的JavaScript作用域問題。 但是,當您將此問題標記為使用Phaser時,建議您使用Phaser Timer事件來避免示波器問題。 特別:
setTimeout(this.rightAnswerGot,1000);
替換為:
this.game.time.events.add(Phaser.Timer.SECOND, this.rightAnswerGot, this);
這將創建一個僅觸發一次的1秒計時器,並在其末尾調用您的函數。 當然,您可以使用1000代替Phaser.Timer.SECOND。
我會想象發生了什么事,就是它在調用this.updateCharacter
並獲取ID之前嘗試調用this.addVariantsHtml
方法。
因此,您可能期望它在運行時類似於:
this.addVariantsHtml(1);
但是它實際上試圖運行
this.addVariantsHtml(this.updateCharacter());
因此,只需執行以下操作:
var id = this.updateCharacter();
this.addVariantsHtml(id);
要么,要么您需要研究方法鏈接/管道,這很復雜,不需要用於這種情況,但是很有趣:)
好吧,我發現了使它起作用的東西!!
這是一個解決方案:
actionOnClick: function (button) {
var log;
if(button.value==this.char_bubble.text) {
var context=this;
setTimeout(function() {
context.addVariantsHtml(context.updateCharacter());
},1000);
} else {
// wrong
swoshsound.play();
}
console.log(log);
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.