Consider the following code:
MyClass.prototype.my_func = function () {
this.x = 10;
$.ajax({
// ...
success: function (data) {
alert(this.x);
}
});
}
It doesn’t work, since apparently this is not bound into the closure’s execution context. I’ve been able to work it around by introducing another variable:
var _this = this;
And this works inside the anonymous function. But looks quite ugly to me. Is there some nice way to handle this?
This may look like the ugly solution for you and there are some walkarounds (such as using
bind()method to change the context), but this is the best solution I know of.Alternatively you can change it to:
or give it more meaningful name, but it would be better (in this case) not to change the context, as you may need it some day.