回调函数中的`this`

时间:2013-01-28 12:09:22

标签: javascript

我以前用过

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

如何在回调函数中访问此值,如下所示?

MyClass.prototype.myMethod1 = function(value) {
   this.getValue("key", function(value2){
       //ooopss! this is not the same here!    
       this._current = value2;
   });
};

3 个答案:

答案 0 :(得分: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;
    });

};

或者您可以让getValue方法执行回调,并将this设置为实例(使用call/apply)。

答案 1 :(得分:2)

在外部作用域中声明一个变量来保存你的:

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

};

答案 2 :(得分:1)

之前将其声明为变量
MyClass.prototype.myMethod1 = function(value) {
var oldThis = this;
 this.getValue("key", function(value2){
    /// oldThis is accessible here.
    });

};