我有一个包含ajax调用的对象文字router
。我想在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(){
},
}
答案 0 :(得分:4)
将context
选项传递给ajax:
$.ajax({
context: this,
/* other options */
}
现在在ajax回调中,this
将引用router
对象。
答案 1 :(得分: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(){
}
}
答案 2 :(得分:0)
使用绑定绑定整个成功回调它将起作用:
(function (response) {
if (response && response.length > 0) {
this.printMovies(response, callback); }
}).bind(this)
答案 3 :(得分:0)
答案 4 :(得分:0)
一种非常常见的方法是将this
分配给函数开头的局部变量。
var self = this;
然后在回调中使用self
代替this
:
self.printMovies(response, callback);