在回调中使用 "this" 与外部变量和垃圾收集器

Using "this" in a callback vs external variable and the garbage collector

我刚刚偶然发现 IndexedDB example on MDN,其中包含以下内容:

function openDb() {
    var req = indexedDB.open(DB_NAME, DB_VERSION);
    req.onsuccess = function (evt) {
        // Better use "this" than "req" to get the result
        // to avoid problems with garbage collection.
        // db = req.result;
        db = this.result;
    };
    // Rest of code omitted for brevity
}

垃圾收集器有什么问题最好避免?

这个建议看起来很奇怪:req 变量引用的对象(与 this 引用的相同)以及匿名函数对象(由 onsuccessonerroronupgradeneeded 属性)将在查询完成并调用回调后立即被垃圾回收。

技术上 - req 表示对该对象的另一个引用;实际上它不会导致任何 "problems with garbage collection".

总而言之:它既不是 "optimisation" 也不是 "micro optimisation",两者的性能相同。

据我所知,如果您引用 'req','openDb' 调用范围绑定到 'onsuccess'(作为父范围),因此您创建了一个闭包。另一方面,如果 - 您仅引用 'this',则可以在退出函数后立即丢弃 'openDb' 调用范围。

可能造成混淆的是 'req' 引用的对象存在于 'openDb' 的生命周期之外 - 它没有在该函数中独占使用。