【发布时间】:2013-06-14 15:47:19
【问题描述】:
我在 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 的范围内?如何访问req.done 内的整个Bubble 对象?目前,我所有的Bubbles 都在一个数组中,所以我可以传入这个数组的索引并以这种方式访问属性(array[i].attribute)。我想有更好的方法来做到这一点。
【问题讨论】:
-
您是否尝试过 context:this,作为 ajax 选项?不确定它在这种情况下是否有效
-
this需要保存在$.ajax()函数之外的某个变量中。var self = this;然后你可以使用self访问this。
标签: javascript ajax oop prototype scoping