`this` in callback functions

I used

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

How do I access the value of this in a callback function as shown below?

 MyClass.prototype.myMethod1 = function(value) { this.getValue("key", function(value2){ //ooopss! this is not the same here! this._current = value2; }); }; 
0
source share
3 answers
 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 can make a getValue way to call back with this set to the instance (using call / apply ).

+3
source

Declare a variable in the outer scope to save this:

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

Declare it as a variable before

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

All Articles