2016-08-13 60 views
2

这吹我的脑海里,检查出来:IFRAME +的instanceof对象今天失败

的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实际上是一个Object)

#foo.bar instanceof Object回报假!!!!

我试过Chrome,Firefox和MS Edge,都有相同的行为。这是为什么发生?这是一种错误吗?

+0

是什么'#foo.bar的instanceof Object'意味着真正的JavaScript –

+0

'的document.getElementById( '富')。酒吧的instanceof Object' 这是正确的,在sandbox2.html –

+0

,当我创建两个文件如你做了,输出是'#foo.bar instanceof Object:true' 'typeof#foo.bar:object' - 是你期望的吗? –

回答

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 - 两者是不同的对象