gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:29:55 25 4
gpt4 key购买 nike

我刚刚偶然发现了 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 表示对该对象的另一个引用;实际上它不会导致任何“垃圾收集问题”。

总而言之:它既不是“优化”也不是“微优化”,两者的性能相同。

关于javascript - 在回调中使用 "this"与外部变量和垃圾收集器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29984478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com