This question is best explained with some code, so here it is:
// a class
function a_class {
this.a_var = null;
this.a_function = a_class_a_function;
}
// a_class::a_function
function a_class_a_function() {
AFunctionThatTakesACallback(function() {
// How to access this.a_var?
});
}
// An instance
var instance = new a_class();
instance.a_function();
From within the callback in AFunctionThatTakesACallback(), how does one access this.a_var?
You’ll need to expand the scope of
thisby creating a local variable that references it, like this:The reason why you need to do this is because the
thisreference within theAFunctionThatTakesACallbackfunction is not the samethisas the current object, it will likely reference the globalwindowobject instead. (usually not what you want).Oh, did I mention that this is called a closure?