2014-03-29 52 views
0

嗨我有以下代码,我在调用一个函数,该函数需要一个带参数的回调函数。基本上,我试图让e的内容进入this.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(); 
+0

可能重复[如何访问正确的\'这\'/上下文内回调?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) –

回答

2

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

解决方案:bind回调函数的目标对象,像这样:

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

这是在范围上不再回调所以要对它的引用,你可以稍后用户。 .bind(this)在现代浏览器中是一个很好的解决方案,但在旧版本的Internet Explorer中可能会失败,因为该方法可能不可用。

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

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

我遇到了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();