0

I used to use

MyClass.prototype.myMethod1 = function(value) {
    this._current = this.getValue("key", function(value2){
        return value2;
    });
};

How do I access the value of this within the callback function like below?

MyClass.prototype.myMethod1 = function(value) {
   this.getValue("key", function(value2){
       //ooopss! this is not the same here!    
       this._current = value2;
   });
};
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Alan Coromano
  • 23,626
  • 48
  • 130
  • 190

3 Answers3

3
MyClass.prototype.myMethod1 = function(value) {
    var that = this;
    this.getValue("key", function(value2){
         //ooopss! this is not the same here!
         // but that is what you want
         that._current = value2;
    });

};

Or you could make your getValue method execute the callback with this set to the instance (using call/apply).

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
2

Declare a variable in the external scope to hold your this :

MyClass.prototype.myMethod1 = function(value) {
    var that = this;
    this.getValue("key", function(value2){
         that._current = value2;
    });

};
Denys Séguret
  • 355,860
  • 83
  • 755
  • 726
1

Declare it as a variable before

MyClass.prototype.myMethod1 = function(value) {
var oldThis = this;
 this.getValue("key", function(value2){
    /// oldThis is accessible here.
    });

};
Dave Hogan
  • 3,195
  • 4
  • 29
  • 53