iframe + instanceof对象失败

时间:2016-08-13 11:41:17

标签: javascript google-chrome firefox iframe microsoft-edge

今天引起了我的注意,请查看:

的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>
&#13;
&#13;
&#13;

sandbox2.html(iframe的内部)

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

现在,打开index.html,转到开发者控制台并输入

document.getElementById("frame").contentDocument.getElementById('foo').bar = {}

typeof #foo.bar返回object(foo实际上是一个对象)

但是#foo.bar instanceof Object会返回 false !!!!

我尝试过Chrome,Firefox和MS Edge,都有相同的行为。为什么会这样?这是某种错误吗?

1 个答案:

答案 0 :(得分:0)

将sandbox2.html更改为

<!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/>
    #foo.bar instanceof parent.Object: <span id="result1"></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('result1').textContent = (document.getElementById('foo').bar instanceof parent.Object).toString();
                document.getElementById('result2').textContent = (typeof document.getElementById('foo').bar).toString();
            }, 100);
        });
    </script>
</body>
</html>

现在您将看到,从主框架更改iframe中的对象会将其从instanceOf对象更改为instanceOf parent.Object - 这两个是不同的对象