JavaScript 这返回未知属性
javascript this returns unknown property
我刚刚写了那段代码,并在警报部分收到一个错误,告诉我,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);
});
}
function Game()
{
this.difficulty = 0;
this.mode = 0;
this.words = new Array();
this.wordsLoaded = $.proxy(this.wordsLoaded, this);
}
var method = Game.prototype;
method.loadWords = function() {
$.ajax({
type:"GET",
url:"word.php",
data:{mode:this.mode, difficulty:this.difficulty},
success: this.wordsLoaded
});
};
method.wordsLoaded = function() {
alert( this.words.length );
};
this
的值在`done()
处理程序中更改,因此它不再是您的对象。您可以通过将this
的副本保存到另一个变量中来修复它,如下所示:
function game()
{
this.difficulty = 0;
this.mode = 0;
this.words = new Array();
this.loadWords = function()
{
var self = this;
//request word pool
$.ajax({
type:"GET",
url:"word.php",
data:{mode:this.mode, difficulty:this.difficulty}
}).done(function(html) {
alert(self.words.length);
});
}
}
通过执行以下操作在内部保存游戏函数:
var _self = game;
这样你就可以_self.difficulty
、_self.words.length
等,他们将能够访问它。
你可以看看
http://javascript.crockford.com/private.html
有关JavaScript中私有,受保护和公共的更多想法,但这里有一个解决方案:
未经测试的代码
function game() {
var difficulty = 0;
var mode = 0;
var words = [];
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);
});
}
}
你也想要一个用于words
的 getter,但基本上有一种方法可以初始化它,通过调用函数和任何其他访问都是通过 getter。
未经测试的代码
函数游戏() { 变量难度 = 0; 变量模式 = 0; 变量单词 = []; var 那 = 这个; this.loadWords = function() { 请求字池 $.ajax({ 类型:"获取", 网址:"单词.php", data:{mode:that.mode, difficulty:that.difficulty} }).done(function(html) { alert(this.words.length); }); } }
我添加了一个that
变量并将其设置为 this
,以帮助包含该值,但在 ajax 调用中,直接调用 mode
变量可能就足够了,但可能需要使用 that
. 此外,函数之前的this
可能是一个问题,不确定,我需要使用调试器来查看实际发生的情况并查看实际使用的内容。
我错过了.ajax调用中的this
,这是最初的问题。
- JavaScript 这返回未知属性
- AngularJS 未知类型错误:无法读取 null 的属性“1”
- 未知的目标实体属性错误
- 如何使属性动态化(在执行代码之前未知)
- 量角器未知错误,从 DOM 中删除属性
- 为什么
- Angular js:->访问解析属性时,angular引发未知提供程序错误
- 属性名称未知的Mustache模板
- 如何在属性名称未知的情况下解析JSON数据
- 在 JavaScript 中的对象中设置具有未知深度的属性值
- 传递未知数量的对象属性
- 如何更改src属性的一部分未知
- 将变量传递给React组件会给出“未知属性error”
- Uncaught InvalidValueError:未知的属性来源
- 访问对象数组中具有未知属性名称的生成属性
- 安全-可以创建具有未知属性的对象
- JS模板和未知属性
- 读取未知属性的名称
- 未知属性@Validation.For("orderName")
- 访问javascript中未知对象的属性