将参数传递给 indexedDB 回调

Passing argument to indexedDB callback

我对 JS 很陌生,对 indexedDB 更陌生。 我的问题是我需要从回调函数中引用一个对象。 因为 "req.onsuccess" 不称为同步,所以 "this" 不引用 Groupobject。 这就是为什么 "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");

感谢您的帮助!

编辑

使用 "bind(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);

那么你的 onSucess 在哪里?让我们尝试在 JS 中绑定、调用、应用。 http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/.