繁体   English   中英

Javascript-如何在ajax调用中将“ this”绑定到对象文字

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

我有一个对象字面量router ,其中包含ajax调用。 我想打电话给其他功能this.printMovies() Ajax调用内部,但是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(){

    },  
}

context选项传递给ajax:

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

现在在ajax回调内部, this将指向router对象。

在这种情况下,此函数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(){

    }
}

将整个成功调用与bind绑定将起作用:

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

您可以使用新的ES6 箭头功能bind

您可能必须在成功或getData函数上执行此操作

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

一个非常常见的方法是指定this在你的函数开头的局部变量。

var self = this;

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

self.printMovies(response, callback);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM