Javascript-如何绑定';这';在对对象文本的ajax调用中
我有一个object literalJavascript-如何绑定';这';在对对象文本的ajax调用中,javascript,jquery,ajax,this,object-literal,Javascript,Jquery,Ajax,This,Object Literal,我有一个object literal路由器,其中包含一个ajax调用。我想在ajax调用中调用其他函数this.printMovies(),但是this引用ajax对象 如何转义它并使这个引用路由器对象本身? var router = { //... init : function() { this.getData("api/movies", "movies", callback); }, getData : function (url, h
路由器
,其中包含一个ajax调用。我想在ajax调用中调用其他函数this.printMovies()
,但是this
引用ajax对象
如何转义它并使这个引用路由器对象本身?
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(){
},
}
使用Bind绑定整个成功回调将正常工作:
(function (response) {
if (response && response.length > 0) {
this.printMovies(response, callback); }
}).bind(this)
您可以使用新的ES6或
您可能必须在success或getData函数上执行此操作
getData : function (url, htmlType, callback) {
...
}.bind(this),
将
context
选项传递给ajax:
$.ajax({
context: this,
/* other options */
}
现在在ajax回调中,
这个
将引用路由器
对象。在本例中,函数getData
将其父对象的上下文保存在这个
关键字中。因此,您可以做的是,将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(){
}
}
一种非常常见的方法是在函数的开头将
这个赋值给一个局部变量
var self = this;
然后在回调中使用self
而不是this
:
self.printMovies(response, callback);
在我的示例中,您可以看到它尝试了this.printMovies(响应,回调).bind(此)
,但它不起作用。它应该是this.printMovies.bind(此,响应,回调)
,但您可能必须在成功函数中执行它否,this
不是router
对象,而是用不同的建议更新的ajax选项对象。您的示例中是否存在语法错误?但是this
即使在外部范围中也指的是ajax选项,而不是router
objectI已经修改了我的答案,用bind绑定整个成功回调(此);尝试在$之前使用$this=this
初始化变量。ajax
ajax调用defn。并将成功中的路由器obj称为$this
,它可以工作!这就是答案@ViolaT它可以工作,但ajax方法作为一个选项。。。使用上下文
右键<代码>上下文
总是一个更好的选择。