Javascript 将参数传递给indexedDB回调
我对JS非常陌生,对indexedDB甚至更新。 我的问题是我需要从回调函数中引用一个对象。 因为“req.onsuccess”不被称为synchron,“this”不引用Groupobject。 这就是“this.units”和其他变量未定义的原因。 一个非常肮脏的解决方法将是一个全局变量,但我只是不愿意这样做。 还有别的办法吗? 也许把一个参数传递给回调函数Javascript 将参数传递给indexedDB回调,javascript,asynchronous,callback,indexeddb,Javascript,Asynchronous,Callback,Indexeddb,我对JS非常陌生,对indexedDB甚至更新。 我的问题是我需要从回调函数中引用一个对象。 因为“req.onsuccess”不被称为synchron,“this”不引用Groupobject。 这就是“this.units”和其他变量未定义的原因。 一个非常肮脏的解决方法将是一个全局变量,但我只是不愿意这样做。 还有别的办法吗? 也许把一个参数传递给回调函数 function Group(owner, pos) { this.name = ""; this.units = [
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");
谢谢你的帮助
编辑
使用“绑定(this)”解决了这个问题
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);
那么你的性欲在哪里?让我们在JS中尝试绑定、调用和应用。
.那么你的产品在哪里?让我们在JS中尝试绑定、调用和应用,解决了我的问题。非常感谢。有没有办法接受这个答案?