2016-08-13 36 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 - 兩者是不同的對象