Notes for a front-end developer, esyou.net

0%

JAVASCRIPT编写属于自己的类型检测函数

不要跟我说类型检测不是很简单吗?好像直接使用typeof就可以检测了,这个有什么难度?但是大家都知道使用typeof检测出来的并无法检测出Arry、Date、RegExp、Error、Null等特殊类型,如我们遇到是arry的类型,检测出来的是object类型。因此我们想要得到更加精确的类型,就必须得自己动手写一个函数出来判断下类型

了解Object.prototype.toString

1
var b = null
2
Object.prototype.toString.call(b) //[object Null]

由Object.prototype.toString的方法我们可以知道这个方法可以获得[object Null],[object Error]等类型。这样我们就可以直接来拼接一个属于我们自己的类型检测函数啦

类型检测函数type

大致的思想是:假如我们检测到的是object,那么就使用Object.prototype.toString去检测,否则就使用typeof进行检测

1
var typeClass = {}
2
"Boolean Number String Function Array Date RegExp Object Error Null Undefined".split(' ').map(function(item, index){
3
  typeClass['[object '+ item +']'] = item.toLowerCase();
4
})
5
6
function type(obj){
7
  var objType = typeof obj ==='object' || typeof obj ==='function' ? typeClass[Object.prototype.toString.call(obj)] || 'object' : typeof obj;
8
  return objType
9
}
10
type(111) //number
11
type('111') //string
12
type([1,2,3]) //array
13
type(null) //null
14
type({a:1}) //object
15
type(new Date()) //date

JQ中的type函数

1
type: function( obj ) {
2
    if ( obj == null ) {
3
       return obj + "";
4
    }
5
    return typeof obj === "object" || typeof obj === "function" ?
6
       class2type[ toString.call( obj ) ] || "object" :
7
       typeof obj;
8
}

JQ中对IE浏览器做了兼容!