问题
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.
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(){
},
}
回答1:
Pass context
option to ajax:
$.ajax({
context: this,
/* other options */
}
Now inside ajax callbacks, this
will refer to router
object.
回答2:
Here in this case, the function getData
holds the context of it's parent object in this
keyword. So what you can do is, store the reference of this
in some variable and use it later. like:
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(){
}
}
回答3:
Bind the entire success call back with bind it will work:
(function (response) {
if (response && response.length > 0) {
this.printMovies(response, callback); }
}).bind(this)
回答4:
A very common approach is to assign this
to a local variable at the beginning of your function.
var self = this;
Then inside your callback use self
instead of this
:
self.printMovies(response, callback);
回答5:
You can use the new ES6 arrow functions, or bind.
You might have to do this on your success or getData function
getData : function (url, htmlType, callback) {
...
}.bind(this),
来源:https://stackoverflow.com/questions/37521320/javascript-how-to-bind-this-inside-an-ajax-call-to-the-object-literal