簡體   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