Javascript之旅——第八站:說說instanceof踩了一個坑

來源:互聯網
上載者:User

Javascript之旅——第八站:說說instanceof踩了一個坑
 前些天寫js遇到了一個instanceof的坑,我們的頁面中有一個iframe,我在index頁面中計算得到了一個array,然後需要傳遞到Flight頁面 這個嵌套的iframe中的一個函數(SearchFlight)中,作為防禦性編程,我需要在SearchFlight函數中進行參數檢測,也就是判斷過來的參數一 定是Array類型。   一:拋出問題 舉個例子,下面有兩個頁面。 Index.html頁面   1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4     <title></title> 5 </head> 6 <body> 7  8     <iframe name="childframe" src="Flight.html"></iframe> 9 10     <script type="text/javascript">11 12         window.onload = function () {13             //航班14             var airplanes = ["MU", "CA", "CZ"];15 16             var result = window.frames[0].flight.SearchFlight(airplanes);17         };18     </script>19 </body>20 </html> Flight.html頁面   1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4     <title></title> 5 </head> 6 <body> 7     <script type="text/javascript"> 8  9         var flight = (function () {10 11             return {12                 SearchFlight: function (arr) {13                     var result = arr instanceof Array;14                     alert(result);15                 }16             };17         })();18     </script>19 </body>20 </html>  很驚訝的發現instanceof居然不能判斷出arr是一個數組,其實我們用肉眼可以看到,壓根它就是一個數組,但是為什麼instanceof卻判斷不出來呢? 我們知道instancof其實是一個js文法糖,我就修改成簡單點的,判斷arr.constructor是否指向Array,於是我把關鍵字改成如下形式,再來看看看效果。  1         var flight = (function () { 2  3             return { 4                 SearchFlight: function (arr) { 5                     //var result = arr instanceof Array; 6  7                     var result = arr.constructor == Array; 8  9                     alert(result);10                 }11             };12         })();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.