0

以前使っていた

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;
   });
};
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に設定されたコールバックをメソッドに実行させることもできます( /を使用)。thiscallapply

于 2013-01-28T12:12:05.387 に答える
2

これを保持するために外部スコープで変数を宣言します:

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 に答える