Javascript - 如何绑定 'this'在对对象字面量的 ajax 调用中 [英] Javascript - how to bind 'this' inside an ajax call to the object literal
本文介绍了Javascript - 如何绑定 'this'在对对象字面量的 ajax 调用中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象文字 router
,包含一个 ajax 调用.我想在 ajax 调用中调用其他函数 this.printMovies()
但 this
引用 ajax 对象.
I have an object literal router
, containing an ajax call. I want to call other functions this.printMovies()
inside the ajax call but this
refer to the ajax object.
如何转义它并使 this
引用 router
对象本身?
How do I escape it and make this
refer to the router
object itself?
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:
Pass context
option to ajax:
$.ajax({
context: this,
/* other options */
}
现在在 ajax 回调中,this
将引用 router
对象.
Now inside ajax callbacks, this
will refer to router
object.
这篇关于Javascript - 如何绑定 'this'在对对象字面量的 ajax 调用中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文