我有一个对象文字 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(){
},
}
最佳答案
将 context
选项传递给 ajax:
$.ajax({
context: this,
/* other options */
}
现在在 ajax 回调中,this
将引用 router
对象。
关于Javascript - 如何在对对象文字的ajax调用中绑定(bind) 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37521320/