0

我以前用

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

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

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

3 回答 3

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)。

于 2013-01-28T12:12:05.387 回答
2

在外部范围内声明一个变量来保存你的 this :

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

};
于 2013-01-28T12:12:07.327 回答
1

之前将其声明为变量

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

};
于 2013-01-28T12:12:33.853 回答