【问题标题】:`this` in callback functions [duplicate]回调函数中的`this`[重复]
【发布时间】:2013-01-28 12:09:21
【问题描述】:

我以前用过

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;
   });
};

【问题讨论】:

  • 您总是可以将this 作为第二个参数传递过来。不确定它是否会起作用。
  • 函数是否匿名真的没有任何关系。

标签: javascript


【解决方案1】:
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)。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      之前声明为变量

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

      【讨论】:

        猜你喜欢
        • 2014-07-31
        • 2012-12-27
        • 2013-09-09
        • 2012-07-14
        • 2020-05-05
        • 2016-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多