回调函数中的`this` [英] `this` in callback functions

查看:110
本文介绍了回调函数中的`this`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经使用

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

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

How do I access the value of this within the callback function like below?

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


推荐答案

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 方法执行 设置为实例(使用 致电 / 申请 )。

Or you could make your getValue method execute the callback with this set to the instance (using call/apply).

这篇关于回调函数中的`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆