Question

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?

Was it helpful?

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?

OTHER TIPS

You could try using the call method of function objects, which lets you specify a value for this:

myFunction.call(this, args...)

But I think that in this case it would probably be more straightforward to pass 'this' in as one of the parameters to the callback.

When you call instance.a_function(), you're really calling a_class_a_function with instance as this, so you can modify a_class_a_function like so:

function a_class_a_function() {
    var self = this;
    AFunctionThatTakesACallback(function() {
        // do something with self.a_var
    });
}

The problem here is that if you attempt to call a_class_a_function without calling it from an instance, then this will likely refer to the global object, window.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top