Search code examples
javascriptajaxoopprototypescoping

Passing object reference inside of another object


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 Bubbles 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.


Solution

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