JavaScript - 如何将'this'绑定到对象字面量内的ajax调用中

3
我有一个对象字面量router,其中包含一个ajax调用。我想在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(){

    },  
}

$.ajax 调用定义之前,尝试使用 $this = this 初始化一个变量。并在成功时将路由器对象称为 $this - Shaunak D
搞定了!这就是答案! - user4296898
@ViolaT 它可以工作,但是ajax方法是一个选项...使用context - A. Wolff
没错,context 总是更好的选择。 - Shaunak D
5个回答

7

context选项传递给ajax:

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

现在,在ajax回调函数中,this将指向router对象。


1
在这种情况下,函数getData通过this关键字持有其父对象的上下文。因此,您可以将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(){

    }
}

0

使用bind绑定整个成功回调,它会起作用:

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

你的例子中是否有语法错误? - user4296898
但是即使在外部范围,this 仍然指的是 ajax 选项,而不是 router 对象。 - A. Wolff
我已经修改了我的答案,使用bind(this)将整个成功回调函数绑定。 - Dhananjaya Kuppu

0

你可以使用新的ES6 箭头函数绑定

你可能需要在你的success或getData函数中这样做。

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

在我的例子中,你可以看到它尝试了 this.printMovies(response, callback).bind(this),但是它不起作用。 - user4296898
1
应该是this.printMovies.bind(this, response, callback),但你可能需要在成功函数中这样做。 - Kruga
不,this 不是 router 对象,而是 ajax 选项对象。 - A. Wolff
更新为不同的建议。 - Kruga

0
一个非常常见的方法是在函数开始时将this分配给一个本地变量。
var self = this;

然后在您的回调函数中使用self而不是this

self.printMovies(response, callback);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接