开发者

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
        }
    }
}
开发者_JS百科

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜