我有一个对象字面量
如何避免这种情况,使
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 Dcontext
。 - A. Wolffcontext
总是更好的选择。 - Shaunak D