因此,我创建了一个对象,该对象在初始化阶段进行AJAX调用以填充其属性.但是,我遇到了一个非常奇怪的行为:我可以打印并看到$.ajax()范围内的属性值很好,但是任何返回属性值的公共方法的返回值均为“ undefined”.
JS代码如下所示:
function MyFunction() {
this.myProperty;
this.init();
}
Myfunction.prototype.getPropertyValue = function () {
alert(this.myProperty); // returns 'undefined'
}
Myfunction.prototype.init = function () {
$.ajax({
type: 'get',
url: "getProperty.PHP",
dataType: "json",
success: function(response) {
this.myProperty = response[0].Property;
alert(this.myProperty) // returns 'Property Name'
}
});
}
我的想法是在$.ajax()范围内,“ this”实际上是指其他内容.因此,我的问题是,如何确保设置了“ this.myProperty”,并且一旦我们超出AJAX范围,就不会丢失其值?
任何帮助深表感谢.
解决方法:
建立值的方式导致“未定义”的部分原因:
var MyFunction = function () {
this.myProperty;
alert(this.myProperty); // undefined!
this.init();
};
在声明属性(或变量)而不指定值时,它们默认为“未定义”.代替:
var MyFunction = function () {
this.myProperty = false;
alert(this.myProperty); // false
this.init();
};
继续进行ajax调用.没错,回调的范围与对象不同.在ajax成功函数中,this指的是用jQuery包装的XHR对象.调用this.myProperty = response [0] .Property时,实际上是在ajax对象上创建一个新属性并设置其值.要解决此问题,您可以使用jQuery ajax对象的context选项,也可以使用javascript bind方法绑定回调函数:
success: function(response) {
this.myProperty = response[0].Property;
}.bind(this)
… 要么:
$.ajax({
type: 'get',
url: "getProperty.PHP",
dataType: "json",
context: this,
success: function(response) {
this.myProperty = response[0].Property;
}
});
在这里尝试:http://jsfiddle.net/SnLmu/
文献资料
在MDN上> bind()-https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
> jQuery.ajax()-http://api.jquery.com/jQuery.ajax/
> MDN的功能和功能范围-https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope