Assuming I have the following:
var object = {
myfunc: function() {
$.ajax({
url: url,
format: format,
success: function() {
console.log(this) // This refers to the ajax call and not "object"
$.ajax({
url: url,
format: format,
success: function() {
console.log(this) // this refers to nested ajax call and not "object"
}
});
}
});
}
}
How to get "this" to reference "object" as opposed to the ajax call?
Use $.proxy() to pass a custom context to a callback function
var object = {
myvar : "hello",
myfunc : function() {
$.ajax({
url : url,
format : format,
success : $.proxy(function() {
console.log(this) // This refers to the ajax
// call and
// not "object"
$.ajax({
url : url,
format : format,
success : function() {
console.log(this) // this
// refers to
// nested ajax call
// and not "object"
}
});
}, this)
});
}
}
Copy the value of this to another variable when you are still in the context where this holds the value you want.
var object = {
myfunc: function() {
var myObject = this;
$.ajax({
Then use that variable (which will be in scope for functions declared inside it, unless they mask it with another variable of the same name) instead.
success: function() {
console.log(myObject);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With