简体   繁体   中英

Launching jQuery inside object method

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM