[英]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.