我在javascript中声明了一个对象方法。 在这个方法里面我想做一个ajax调用,当调用完成后,修改这个对象的一些属性。
Bubble.prototype.draw = function(){
console.log(this.attribute) // -> works fine
var req = $.ajax({
url: "someFile.php",
type: "post",
data: someData
});
// handle response
req.done(function (response, textStatus, jqXHR){
console.log(this.attribute) // -> not in the scope, obviously
});
}
如何将this.attribute
置于req.done
的范围内?如何访问Bubble
内的整个req.done
对象?目前,我的所有Bubble
都在一个数组中,因此我可以传入此数组的索引并以这种方式访问属性(array[i].attribute
)。我想有更好的方法可以做到这一点。
答案 0 :(得分:3)
Bubble.prototype.draw = function () {
console.log(this.attribute) // -> works fine
var req = $.ajax({
url: "someFile.php",
type: "post",
data: someData
}),
self = this; //save this object
// handle response
req.done(function (response, textStatus, jqXHR) {
console.log(self.attribute) //access parent this
});
}
答案 1 :(得分:3)
这是因为当调用ajax回调时,执行上下文不同,这意味着回调方法中的this
关键字指向另一个对象,而不是指向所需的气泡对象。
有两种解决方案,如下所示
使用$ .proxy将自定义执行上下文传递给回调处理程序
Bubble.prototype.draw = function(){
console.log(this.attribute) // -> works fine
var req = $.ajax({
url: "someFile.php",
type: "post",
data: someData
});
// handle response
req.done($.proxy(function (response, textStatus, jqXHR){
console.log(this.attribute) // -> not in the scope, obviously
}, this));
}
或使用闭包变量
Bubble.prototype.draw = function(){
console.log(this.attribute) // -> works fine
var req = $.ajax({
url: "someFile.php",
type: "post",
data: someData
});
var _this = this;
// handle response
req.done(function (response, textStatus, jqXHR){
console.log(_this .attribute) // -> not in the scope, obviously
});
}
答案 2 :(得分:1)
只需将this.attribute
变量复制到另一个范围变量,就像这样。
Bubble.prototype.draw = function(){
console.log(this.attribute) // -> works fine
_this = this.attribute;
var req = $.ajax({
url: "someFile.php",
type: "post",
data: someData
});
// handle response
req.done(function (response, textStatus, jqXHR){
console.log(_this) // -> not in the scope, obviously
});
}
答案 3 :(得分:1)
看起来像这样,这似乎是使用上下文选项的原生方式:
Bubble.prototype.draw = function () {
console.log(this.attribute) // -> works fine
var req = $.ajax({
url: "someFile.php",
type: "post",
data: someData,
context: this
});
// handle response
req.done(function (response, textStatus, jqXHR) {
console.log(this.attribute);
});
}