我有一个包含AJAX帖子的JS类。我正在尝试使用this
从post函数中引用类成员,但它似乎不起作用。
例如,从中:
function Classy() {
this.goal = 0;
$.post(
"class/initial.php",
function(back) {
this.goal = back.goal;
}, "json");
this.SampleFunction = function() {
alert(this.goal);
}
}
tester = new Classy();
tester.SampleFunction();
警告框输出值0
,即使这绝对不是从php文件返回的内容。我认为问题是我需要this
之外的其他内容来引用父类。有人有什么想法吗?
答案 0 :(得分:2)
function Classy() {
this.goal = 0;
// jQuery.proxy returns a function
$.post("class/initial.php", $.proxy(function (back) {
this.goal = back.goal;
}, this), "json");
// ^-------- is manually set in your handler
this.SampleFunction = function () {
alert(this.goal);
}
}
您可以使用jQuery.proxy()
[docs]方法确保正确的this
值。
另一种可能性是使用长格式jQuery.ajax()
[docs]方法,您可以在其中设置context:
参数,以便为您提供所需的this
值。
function Classy() {
this.goal = 0;
$.ajax({
type:'POST',
url:"class/initial.php",
dataType: 'json',
context: this, // <--set the context of the callbacks
success: function (back) {
this.goal = back.goal;
}
});
this.SampleFunction = function () {
alert(this.goal);
}
}
答案 1 :(得分:1)
this
表示jQuery在回调中调用的匿名函数内部的不同内容。所以先抓住它:
function Classy() {
this.goal = 0;
var $t = this;
$.post(
"class/initial.php",
function(back) {
$t.goal = back.goal;
}, "json");
this.SampleFunction = function() {
alert(this.goal);
}
}
答案 2 :(得分:0)
在事件处理程序中,this
指的是触发事件的对象。 AJAX成功回调实际上是执行工作的XMLHttpRequest对象的事件处理程序,因此在这种情况下,this
引用XMLHttpRequest对象(实际上是jqXHR对象)。要获取对象的引用,请将this
分配给可在事件处理程序中引用的变量:
function Classy() {
this.goal = 0;
var that = this;
$.post("class/initial.php", function(back) {
that.goal = back.goal;
}, "json");
}