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
});
}