Javascript - 如何绑定'这个'在ajax调用对象文字

时间:2016-05-30 08:45:33

标签: javascript jquery ajax this object-literal

我有一个包含ajax调用的对象文字router。我想在ajax调用中调用其他函数this.printMovies(),但this引用ajax对象。

如何将其转义并让this引用router对象本身?

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(){

    },  
}

5 个答案:

答案 0 :(得分:4)

context选项传递给ajax:

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

现在在ajax回调中,this将引用router对象。

答案 1 :(得分:1)

在这种情况下,函数getDatathis关键字中保存其父对象的上下文。所以你可以做的是,将this的引用存储在某个变量中,稍后再使用它。像:

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(){

    }
}

答案 2 :(得分:0)

使用绑定绑定整个成功回调它将起作用:

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

答案 3 :(得分:0)

您可以使用新的ES6 arrow functionsbind

您可能必须在您的成功或getData函数

上执行此操作
&str

答案 4 :(得分:0)

一种非常常见的方法是将this分配给函数开头的局部变量。

var self = this;

然后在回调中使用self代替this

self.printMovies(response, callback);