开发者

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?


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜