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
  • 795,719
  • 175
  • 1,089
  • 1,143
Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

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
  • 630,263
  • 148
  • 957
  • 1,375
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
  • 372,613
  • 87
  • 782
  • 758
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,201
  • 6
  • 29
  • 54