[英]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
對象。
在這種情況下,此函數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(){
}
}
將整個成功調用與bind綁定將起作用:
(function (response) {
if (response && response.length > 0) {
this.printMovies(response, callback); }
}).bind(this)
一個非常常見的方法是指定this
在你的函數開頭的局部變量。
var self = this;
然后在回調中使用self
代替this
:
self.printMovies(response, callback);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.