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);
那么你的onSucess在哪里?让我们尝试绑定,调用,申请在JS http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/ –
这解决了我的问题。谢谢!有没有办法接受这个答案? – Coding