function checkedType(target) {
return Object.prototype.toString.call(target).slice(8, -1)
}
Object.prototype.toString.call( ) ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
总结:
当前总结的方法是最精准的,但是还有别的一些方法都有一些缺点不能通用
-
typeof 不能判断null、array等
-
instanceof 不能检测null 和 undefined
-
constructor 这个主要体现在把类的原型进行重写,在重写的过程中很有可能出现把之前的 constructor给覆盖了,这样检测出来的结果就是不准确的