【发布时间】:2016-08-13 11:41:16
【问题描述】:
今天让我大吃一惊,看看吧:
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>framed</title>
</head>
<body>
<iframe src="sandbox2.html" frameborder="0" width="640" height="480" id="frame"></iframe>
</body>
</html>
sandbox2.html(iframe 内部)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>instanceof Object FAIL DEMO</h1>
<div id="foo"></div>
#foo.bar instanceof Object: <span id="result"></span>
<br/>
typeof #foo.bar: <span id="result2"></span>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('foo').bar = { test: 'aaa' };
setInterval(function() {
document.getElementById('result').textContent = (document.getElementById('foo').bar instanceof Object).toString();
document.getElementById('result2').textContent = (typeof document.getElementById('foo').bar).toString();
}, 100);
});
</script>
</body>
</html>
现在,打开 index.html,进入开发者控制台并输入
document.getElementById("frame").contentDocument.getElementById('foo').bar = {}
typeof #foo.bar 返回object(而 foo 实际上是一个对象)
但是#foo.bar instanceof Object 返回 false!!!!
我尝试过 Chrome、Firefox 和 MS Edge,都具有相同的行为。为什么会这样?这是某种错误吗?
【问题讨论】:
-
#foo.bar instanceof Object在真正的 javascript 中是什么意思 -
document.getElementById('foo').bar instanceof Object就在 sandbox2.html 中 -
当我像你一样创建两个文件时,输出是
#foo.bar instanceof Object: truetypeof #foo.bar: object- 这是你所期望的吗? -
是的,这正是我所期望的,但是您是否从
index.html的控制台中调用了document.getElementById("frame").contentDocument.getElementById('foo').bar = {}? -
那是因为它不再是 [window.]Object 的实例 - 它是 parent.Object 的实例
标签: javascript google-chrome firefox iframe microsoft-edge