I'm declaring an object method in javascript. Inside of this method I want to do an ajax call and, when the call is done, to modify some attributes of this object.
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
});
}
How can I put this.attribute
in the scope of req.done
? How can I access the whole Bubble
object inside of req.done
? Currently, all of my Bubble
s are in an array so I could just pass in the index of this array and access the properties this way ( array[i].attribute
). I guess there is a much better way to do this.
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
});
}
It is because when the ajax callback is called the execution context is different, meaning the this
keyword inside the callback method points to another object, not to the desired bubble object.
There are two solutions for this as shown below
Use $.proxy to pass a custom execution context to the callback handler
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));
}
Or use a closure variable
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
});
}
just copy this.attribute
variable to another scope variable like this.
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
});
}
Looks like it works like this, which seems the native way of doing it, using context option:
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);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.