2014-03-29 87 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();