我刚刚编写了那段代码,并在警报部分收到错误,告诉我 this.words 未定义。 我猜想 jquery 部分更改了“this”值,因为在注释所在的位置,我可以访问该数组。
现在我卡住了,因为我不想使单词属性成为全局的(是什么让它运行)。 所以我想向您询问一种在保持“OOP”风格的同时解决问题的方法。
function game()
{
this.difficulty = 0;
this.mode = 0;
this.words = new Array();
this.loadWords = function()
{
//request word pool
$.ajax({
type:"GET",
url:"word.php",
data:{mode:this.mode, difficulty:this.difficulty}
}).done(function(html) {
alert(this.words.length);
});
}
}
最佳答案
这似乎是一个范围问题。 this
不再引用 .done
函数中的游戏对象。尝试一下
this.loadWords = function()
{
var that = this;
//request word pool
$.ajax({
type:"GET",
url:"word.php",
data:{mode:this.mode, difficulty:this.difficulty}
}).done(function(html) {
alert(that.words.length);
});
}
关于javascript 这返回未知属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11850592/