Javascript内部闭包中的parentNode丢失了吗?铬虫?
在Chrome中执行以下测试HTML页面时,我在调试控制台中看到以下内容:Javascript内部闭包中的parentNode丢失了吗?铬虫?,javascript,html,google-chrome,garbage-collection,closures,Javascript,Html,Google Chrome,Garbage Collection,Closures,在Chrome中执行以下测试HTML页面时,我在调试控制台中看到以下内容: Has parent? true Has parent? false 我是否正确地假设这是一个Chrome bug(在其他浏览器中不会发生),或者Chrome出于某种原因有权这么做?这导致了我的一个web应用程序出现了一个bug,我最终隔离了这个片段来重新编写核心问题 以下是测试页面: 函数testDoodle(){ var testParentEl=document.createElement('div'); v
Has parent? true
Has parent? false
我是否正确地假设这是一个Chrome bug(在其他浏览器中不会发生),或者Chrome出于某种原因有权这么做?这导致了我的一个web应用程序出现了一个bug,我最终隔离了这个片段来重新编写核心问题
以下是测试页面:
函数testDoodle(){
var testParentEl=document.createElement('div');
var testChildEl=testParentEl.appendChild(document.createElement('div'));
document.body.innerHTML+=('Has parent?'+!!testChildEl.parentNode+'
');
log('Has parent?'+!!testChildEl.parentNode);
setTimeout(函数(){
document.body.innerHTML+=('Has parent?'+!!testChildEl.parentNode+'
');
log('Has parent?'+!!testChildEl.parentNode);
},
2000);
返回;
}
testDoodle();
我的猜测是testChildEl.parentNode
没有强烈引用testParentEl
,因此它是垃圾收集的
在超时内引用testParentEl
,并在testChildEl
上添加对testParentEl
的强引用,这两种方法都为我解决了问题:
(函数testDoodle(){
var testParentEl=document.createElement('div');
var testChildEl=testParentEl.appendChild(document.createElement('div'));
setTimeout(函数(){
testParentEl;//防止对其进行垃圾收集
document.write('Has parent?'+!!testChildEl.parentNode);
}, 100);
})();代码>我相信Chrome v50最终解决了这一问题(或者至少在更新后我还无法重新编程)。在Chrome 48中对我有效,OSXI无法复制(Chrome 48.0.2564.109)。你确定调用之间没有变异testParentEl吗?我应该提到我正在使用Chrome 49.0.2623.87 m(64位)在Windows 7上进行测试。此外,我应该提到,有时它显示true/true,有时显示true/false。您可能需要重新加载页面几次才能看到问题。我不确定,但调试工具(控制台)也可能需要打开。对于我来说,相同的浏览器版本(Windows 10)更新为Chrome 49,但仍然无法复制。这听起来真的像是一个bug。Javascript中已经有“强”和“弱”引用了吗?我的理解是没有。我也发现这个问题可以通过在闭包中显式引用testPartEl来解决。是的,我确信这是一只虫子。很明显,一些Chrome优化坏了。我只是不知道为什么没有人会被它咬到。@logidelices6引入了weakset和weakmap,它们存储对对象的弱引用。除此之外,它完全依赖于实现,规范不需要垃圾收集器。根据定义,应该无法检测对象是否已被垃圾收集器,因此这是一个bug。