jquery代码阅读之jquery.type

来源:互联网 发布:淘宝营销团队 编辑:程序博客网 时间:2024/04/29 15:06

jquery代码阅读之jquery.type
jquery 源码中有众多地方采用jquer.type 来判断类型 API 参考文档在[这里],(http://api.jquery.com/jQuery.type/)从文档里可以看出改方法对各种类型的返回,在jquery源码中其判断类型的核心方法为Object.prototype.toString 通过toString来判断类型,主要实现方式为:

/*1:定义class2type*/toString = Object.prototype.toString,class2type = {};/*2为class2tpye赋值class2type = {    [object Array]: "array",    [object Boolean]: "boolean",    [object Date]: "date",    [object Function]: "function",    [object Number]: "number",    [object Object]: "object",    [object RegExp]: "regexp",    [object String]: "string"}*/jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {        class2type[ "[object " + name + "]" ] = name.toLowerCase();});/*type定义 调用toStringObject.prototype.toString.call("hello") "[object String]"Object.prototype.toString.call({hello:"hello"}) "[object Object]"Object.prototype.toString.call([1,2,3]) "[object Array]"*/jQuery.extend({    /*--------其他API-----------*/      type: function( obj ) {        return obj == null ?                String( obj ) :                class2type[ toString.call(obj) ] || "object"; //String(null) 返回"null"       },     /* 直接调用jQuery.type的方法*/    isFunction: function( obj ) {        return jQuery.type(obj) === "function";    },    /*对于支持isArray的浏览器使用isArray 否则使用jQuery.type*/    isArray: Array.isArray || function( obj ) {        return jQuery.type(obj) === "array";    },}
0 0
原创粉丝点击