Javascript 回调函数中的访问变量

Javascript 回调函数中的访问变量,javascript,callback,Javascript,Callback,您好,我有下面的代码,其中我调用了一个函数,该函数接受一个回调函数,该回调函数接受一个参数。基本上,我正在尝试将e的内容放入这个.items中,但我无法逃避回调函数 function stash(){ this.items = new Array(); this.get = function(){ opr.stash.query({},function(e){ console.log(this.items); //this is not defin

您好,我有下面的代码,其中我调用了一个函数,该函数接受一个回调函数,该回调函数接受一个参数。基本上,我正在尝试将e的内容放入这个.items中,但我无法逃避回调函数

function stash(){
    this.items = new Array();

    this.get = function(){
      opr.stash.query({},function(e){
         console.log(this.items); //this is not defined
      });
    }
}

s = new stash();
s.get();

问题:回调函数的上下文对象(
this
)不再引用
get()
方法的上下文对象

解决方案:向目标对象调用回调函数,如下所示:

opr.stash.query({},(function(e){
  console.log(this.items);
}).bind(this));

这已不在回调的作用域中,因此请对其进行引用,以便以后使用。绑定(this)在现代浏览器中是一个很好的解决方案,但在旧版本的Internet Explorer中可能会失败,因为该方法可能不可用

function stash(){
        var self = this; 
        this.items = new Array();

        this.get = function(){
          opr.stash.query({},function(e){
             console.log(self.items); 
          });
        }
    }

我在d3.chart中遇到了类似的问题

我目前没有访问opr.stash的权限,因此我无法先测试它,但您是否尝试过以下方法:

function stash()
{
    var myStash = this;

    myStash.items = new Array();

    myStash.get = function(){
       opr.stash.query({},function(e){
       console.log(myStash.items); //this is not defined
      });
    }
}

s = new stash();
s.get();
可能重复的