当我在 Chrome 中执行以下测试 HTML 页面时,我在调试控制台中看到以下内容:
Has parent? true
Has parent? false
我是否正确地假设这是一个 Chrome 错误(在其他浏览器中不会发生),或者 Chrome 是否出于某种原因有权这样做?它导致我的一个网络应用程序出现错误,我最终分离出这个片段以重现核心问题。
这是测试页面:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body class="">
<script>
function testDoodle() {
var testParentEl = document.createElement('div');
var testChildEl = testParentEl.appendChild(document.createElement('div'));
document.body.innerHTML+=('Has parent? ' + !!testChildEl.parentNode+'<br>');
console.log('Has parent? ' + !!testChildEl.parentNode);
setTimeout(function() {
document.body.innerHTML+=('Has parent? ' + !!testChildEl.parentNode+'<br>');
console.log('Has parent? ' + !!testChildEl.parentNode);
},
2000);
return;
}
testDoodle();
</script>
</body>
</html>
编辑:我应该提到我正在使用 Chrome 49.0.2623.87 m(64 位)在 Windows 7 上进行测试。还能够使用 Chrome 49 在 OSX 10.11.2 上重现。
另外,我应该提一下,有时它显示真/真,有时显示真/假。您可能需要重新加载页面几次才能看到该问题。我不确定,但可能还需要打开调试工具(控制台)。
非常感谢。
最佳答案
我的猜测是 testChildEl.parentNode
没有强烈引用 testParentEl
,所以它被垃圾收集了。
在超时内引用 testParentEl
并在 testChildEl
上添加对 testParentEl
的强引用为我解决了这个问题:
(function testDoodle() {
var testParentEl = document.createElement('div');
var testChildEl = testParentEl.appendChild(document.createElement('div'));
setTimeout(function() {
testParentEl; // Prevents it from being garbage collected
document.write('Has parent? ' + !!testChildEl.parentNode);
}, 100);
})();
(function testDoodle() {
var testParentEl = document.createElement('div');
var testChildEl = testParentEl.appendChild(document.createElement('div'));
testChildEl.strongParent = testParentEl; // Prevents garbage collection
setTimeout(function() {
document.write('Has parent? ' + !!testChildEl.parentNode);
}, 100);
})();
关于javascript - parentNode 在 Javascript 内部闭包中丢失? Chrome 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902690/