views:

22

answers:

1

Hello, let's assume that we have object like this below:

function foo( some_var ) {
    this.some_var = some_var;
}

Now we add some method via prototype:

foo.prototype.method = function( value ) {
    this.some_var += value;
}

Then, we have method with which I have some problems:

foo.prototype.problematic = function( args ) {
    //using jQuery $.getJSON function
    $.getJSON( 'http://url.com', args, function( data ) {
        for( var i in data ) {
            this.method( data[i].value );
            // we have error in console: "this.method is not a function"
            // this doesn't point to object foo, but to data which are returned by $.getJSON function
        }
    }
}

As I mentioned in comments above, we have an error in Firebug console: "this.method is not a function". This is because our "this" doesn't point to object foo. I don't want to make something like this:

var self = this;

And then using variable self instead of this, because I am making a lot o changes inside object variables.

Thanks in advance for your help. Cheers

A: 

You could use .ajax() instead of .getJSON() as that would allow you to specify the context:

var self = this; // I know you don't want to use self, so let's use this as
                 // the context for the async callback
$.ajax({ 
    context: this, 
    dataType: "json",
    success: function(){        
        for( var i in data ) {
            this.method( data[i].value );    // this == self
        }
}});
GenericTypeTea
thanks, trick with context: this works perfectly
Mateusz Rutkiewicz