Javascript - how to bind 'this' inside an ajax call to the object literal

倾然丶 夕夏残阳落幕 提交于 2019-12-12 17:29:17

问题


I have an object literal router, containing an ajax call. I want to call other functions this.printMovies() inside the ajax call but this refer to the ajax object.

How do I escape it and make this refer to the router object itself?

var router = {  

    //...
    init : function() {
        this.getData("api/movies", "movies", callback);
    },
    getData : function (url, htmlType, callback) {
        $.ajax({
            url: url,
            dataType: 'json',
            success: function (response) {
                if (response && response.length > 0) {
                    this.printMovies(response, callback); //'this' refers to ajax
                    this.printMovies(response, callback).bind(this) //still doesn't work
                }
            },
            error: function (response) { console.log("Error:" + response); }
        });
    },
    printMovies : function(){

    },  
}

回答1:


Pass context option to ajax:

$.ajax({
  context: this,
  /* other options */
}

Now inside ajax callbacks, this will refer to router object.




回答2:


Here in this case, the function getData holds the context of it's parent object in this keyword. So what you can do is, store the reference of this in some variable and use it later. like:

var router = {  

    //...
    init : function() {
        this.getData("api/movies", "movies", callback);
    },
    getData : function (url, htmlType, callback) {
        var mainObj = this; // line to be noticed

        $.ajax({
            url: url,
            dataType: 'json',
            success: function (response) {
                if (response && response.length > 0) {
                    // parent object to be used
                    mainObj.printMovies(response, callback); //'this' refers to ajax
                }
            },
            error: function (response) { console.log("Error:" + response); }
        });
    },
    printMovies : function(){

    }
}



回答3:


Bind the entire success call back with bind it will work:

(function (response) {
            if (response && response.length > 0) {
                this.printMovies(response, callback);                                     }
        }).bind(this)



回答4:


A very common approach is to assign this to a local variable at the beginning of your function.

var self = this;

Then inside your callback use self instead of this:

self.printMovies(response, callback);



回答5:


You can use the new ES6 arrow functions, or bind.

You might have to do this on your success or getData function

getData : function (url, htmlType, callback) {
  ...
}.bind(this),


来源:https://stackoverflow.com/questions/37521320/javascript-how-to-bind-this-inside-an-ajax-call-to-the-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!