I'm trying to call an instance method a() from within a jQuery ajax call. But when I do so, it says that the method is not defined. I think it's because a() is not within the scope of $. But I thought it would be part of the scope chain. How can a() be within scope?
function Z() {
this.x = 0
this.a = function() {
return this.x;
}
this.b = function() {
$.ajax({
...
success: function(data, textStatus, xhr) {
this.a(); //a() is not defined
},
...
});
}
}
z = new Z();
z.b();
Most people will suggest a trick like var that = this;, but I prefer using function binding to achieve the same end more elegantly and clearly.
Create a local function a, which is this.a bound to this:
function Z() {
this.x = 0
this.a = function() {
return this.x;
}
this.b = function() {
var a = this.a.bind(this);
$.ajax({
...
success: function(data, textStatus, xhr) {
a();
},
...
});
}
}
z = new Z();
z.b();
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