Search code examples
javascriptclassclass-members

How to get access to this class member from within a callback?


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?


Solution

  • You'll need to expand the scope of this by creating a local variable that references it, like this:

    function a_class_a_function() {
       var self = this;
       AFunctionThatTakesACallback(function() {
          console.log(self.a_var); 
       });
    }
    

    The reason why you need to do this is because the this reference within the AFunctionThatTakesACallback function is not the same this as the current object, it will likely reference the global windowobject instead. (usually not what you want).

    Oh, did I mention that this is called a closure?