secrets of the javascript Ninja(Function Type)(javascript忍者的秘密)
大多數情況下,typeof就可以完成檢查函數類型的工作,例如:
function ninja(){} alert(typeof ninja);
但是根據瀏覽器的不同,我們可以發現以下集中情況
- 在firefox2和firefox3中,如果檢測一個<object/>類型的元素,將會檢測出來是一個function
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>無標題文檔</title> <mce:script type="text/javascript"><!-- window.onload=function(){ var o=document.getElementById("doc_html"); alert(typeof o); } // --></mce:script> </head> <body> <object name="doc_html" data=" gledit.htm" width=530 height=320 type=text/x-scriptlet VIEWASTEXT></object> </body> </html>
- firefox2正則表達式會被認為是一個function;但是在firefox3中會被認為是object
- IE6和IE7中一些dom元素的方法會被認為一個object //typeof /test/=='function'
- safari3中認為NodeList為function如:typeof document.body.childNodes =="function"
縱觀以上所有情況,我們可以寫出一個通用的函數來檢測某個值是否是函數
function isFunction( fn ) { return !!fn && !fn.nodeName && fn.constructor != String && fn.constructor != RegExp && fn.constructor != Array && /function/i.test( fn + "" ); }
最後更新:2017-04-02 00:06:44