Accessing `this` in Ajax callback, all within an Object

后端 未结 3 2132
夕颜
夕颜 2020-12-14 12:34

I\'m dealing with a problem about an Ajax callback inside of an Object. Please consider this code :

Search.prototype =
{
    ask : function( query )
    {
           


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 12:51

    You can use the ES5 .bind function to set this correctly:

    $.ajax(...).done(this.loadResults.bind(this));
    

    (use the shim at the above link, or the jQuery $.proxy equivalent on older browsers).

    Alternatively, add context: this to the $.ajax options:

    $.ajax({
        ...,
        context: this
    }).done(this.loadResults);
    

    Note that in either case you will override jQuery's default behaviour of passing the ajax option object in this.

    p.s. it's also good practise to return the result of the $.ajax() chain so that the user of your object can chain additional callbacks (e.g. a .fail handler) to it.

提交回复
热议问题