由于具体实现上的问题,在实际的项目应用中,typeof只有两个用途,就是检测一个元素是否为undefined,或者是否为function。 为何呢? JavaScript Garden整理出来了如下表格: Value function typeof ------------------------------------- "foo" String string new String("foo") String object 1.2 Number number new Number(1.2) Number object true Boolean boolean new Boolean(true) Boolean object new Date() Date object new Error() Error object [1,2,3] Array object new Array(1, 2, 3) Array object new Function("") Function function /abc/g RegExp object new RegExp("meow") RegExp object {} Object object new Object() Object object 所以我们一般用“鸭子类型”来做流程控制,好晚了,不多讲,去搜一下吧。 一定要区分这些东西? Object.prototype.toString()有一个妙用,如果我们以某个特别的对象为上下文来调用该函数,它会返回正确的类型。我们需要做的就是手动处理其返回的字符串,最终便能获得typeof应该返回的正确字符串。 可以用来区分:Boolean, Number, String, Function, Array, Date, RegExp, Object, Error等等。 jQuery.type()就是这样实现的。以下代码从jQuery源码中抽取出来,可以直接用。 var class2type = {} ; "Boolean Number String Function Array Date RegExp Object Error".split(" ").forEach(function(e,i){ class2type[ "[object " + e + "]" ] = e.toLowerCase(); }) ; //当然为了兼容IE低版本,forEach需要一个polyfill,不作细谈了。 function _typeof(obj){ if ( obj == null ){ return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ class2type.toString.call(obj) ] || "object" : typeof obj; } 使用结果: _typeof(new String()) ->"string" _typeof("123") ->"string" _typeof(new RegExp()) ->"regexp" _typeof(null) ->"null"