传统的typeof
不能很准确的判断一个参数是否是函数。
参照下图:
为什么null
会是object
呢?
MDN
给出了答案:因为null是空指针,而空指针在大多数平台中使用0x00表示,而js在实现初期通过用 0 作为对象的标签,所以对null也被判断为object。
为什么说typeof
在判断function
的时候不准确呢?来看看jQuery
源码里的说明:
var isFunction = function isFunction( obj ) {
// Support: Chrome <=57, Firefox <=52
// In some browsers, typeof returns "function" for HTML <object> elements
// (i.e., `typeof document.createElement( "object" ) === "function"`).
// We don't want to classify *any* DOM node as a function.
// Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5
// Plus for old WebKit, typeof returns "function" for HTML collections
// (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756)
return typeof obj === "function" && typeof obj.nodeType !== "number" &&
typeof obj.item !== "function";
};
所以在判断是否是function
之前,必须先排除可能是html 元素
的可能性。
typeof obj.nodeType !== "number"
:如果是DOM
对象,那么obj.nodeType
返回的是数字。(具体参见DOM
结点类型)。
typeof obj.item !== "function"
:如果是DOM Collections
的话,那么typeof obj.item
会返回function