首先,在各個瀏覽器中 HTML元素節點 的返回值有所差別:node
一、Firefox2 和 Firefox3 git
在這兩個瀏覽器中,用 typeof 檢測 HTML 對象元素的類型,獲得是一個不精確的 「function」 結果,而不是 「object」,如 HTMLDocument。如: github
alert(typeof HTMLDocument);
// 在 Firefox2 中結果是 "function";
// 在 Firefox3 中結果是 "object";
二、Firefox2 正則表達式
對於正則表達式,在該瀏覽器中返回的結果是 「function」(在 Firefox3 中結果是 「object」),如: 瀏覽器
var reg = /test/;
alert(typeof reg);
// 在 Firefox2 中結果是 "function";
// 在 Firefox3 中結果是 "object";
注:本人在 safari 中測試,其結果也是 「function」。 app
三、IE6 和 IE7 函數
在 IE 中對 DOM 元素使用 typeof 方法,獲得的結果是 「object」。如: 測試
alert(typeof document.getElementsByTagName("body")[0].getAttribute);
// 結果是 "object"
四、Safari 3
safari 認爲 DOM 元素的 NodeList 是一個函數,如: 優化
alert(typeof document.body.childNodes);
// 結果是 "function"
很明顯,若是你要測試一個對象是否爲函數,使用 typeof 方法並不能從真正意義上保證測試結果。那麼,咱們就須要一種在全部瀏覽器中都能保證測試結果的解決方案。咱們知道 function 自己有 apply() 和 call() 兩種方法,但這兩個方法在 IE 中存在問題的函數中並不存在,試試下面的測試: spa
alert(typeof document.getElementsByTagName("body")[0].getAttribute.call)
// 在 IE 中結果是 "undefined"
因此有一種方法:
function isFunction(fn) {
return !!fn && !fn.nodeName && fn.constructor != String &&
fn.constructor != RegExp && fn.constructor != Array &&
/function/i.test(fn + "");
}
參考: http://www.jb51.net/article/19841.htm
此外還有一種方法:
/** * 判斷對象是否爲函數,若是當前運行環境對可調用對象(如正則表達式) * 的typeof返回'function',採用通用方法,不然採用優化方法 * * @param {Any} arg 須要檢測是否爲函數的對象 * @return {boolean} 若是參數是函數,返回true,不然false */ function isFunction(arg) { if (arg) { if (typeof (/./) !== 'function') { return typeof arg === 'function'; } else { return Object.prototype.toString.call(arg) === '[object Function]'; } } // end if return false; }