2017-04-23 106 views
1

我對JS很新,甚至更新到indexedDB。 我的問題是,我需要從一個回調函數內引用一個對象。 因爲「req.onsuccess」不叫同步,「this」不是指Group對象。 這就是爲什麼「this.units」和其他變量未定義。 一個非常骯髒的解決方法將是一個全局變量,但我只是不願意這樣做。 還有別的辦法嗎? 也許傳遞一個參數到回調?將參數傳遞給indexedDB回調

function Group(owner, pos) 
{ 
    this.name = ""; 
    this.units = []; 
    //... 
} 
Group.prototype.addUnit = function(unit) 
{ 
    let req = db.transaction(["units"]).objectStore("units").get(unit); 
    req.onsuccess = function(event) 
    { 
     let dbUnit = event.target.result; 
     if (dbUnit) 
     { 
      this.units.push(dbUnit);//TypeError: this.units is undefined 
      if (this.name == "") 
      { 
       this.name = dbUnit.name; 
      } 
     } 
    }; 
}; 
myGroup = new Group(new User(), [0,0]); 
myGroup.addUnit("unitname"); 

感謝您的幫助!

編輯

使用 「綁定(本)」 解決了這個問題。

Group.prototype.addUnit = function(unit) 
{ 
    let req = db.transaction(["units"]).objectStore("units").get(unit); 
    req.onsuccess = function(event) 
    { 
     let dbUnit = event.target.result; 
     if (dbUnit) 
     { 
      this.units.push(dbUnit);//TypeError: this.units is undefined 
      if (this.name == "") 
      { 
       this.name = dbUnit.name; 
      } 
     } 
    }; 
}.bind(this); 
+1

那麼你的onSucess在哪裏?讓我們嘗試綁定,調用,申請在JS http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/ –

+0

這解決了我的問題。謝謝!有沒有辦法接受這個答案? – Coding

回答