jQuery源码分析(3)

把以前看的jQuery源码的分析笔记搬到博客上,重温经典,也是为了方便查询。

var class2type = {}, 
     core_toString = class2type.toString;

jQuery.extend({
  isFunction: function(obj) {
    return jQuery.type(obj) === 'function';
  }
  isArray: Array.isArray || function(obj) {
    return jQuery.type(obj) === 'array';
  }

  type: function(obj){
    if (obj == null) {
      return String(obj);
    }
    return typeof obj === 'object' || typeof obj === 'function'  ?
              class2type[core_toString.call(obj)]  ||  'object'  :  typeof obj;
  }
});
 
typeof 不能区分Array,RegExp等object类型,jquery为了扩展typeof的能力,添加了$.type;
针对特殊的对象(如null,Array,RegExp)也进行精准的类型判断;
运用钩子机制,判断类型前,将常见类型存入hash表class2type中。
 
jQuery.each('Boolean Number String Function Array Date RegExp Object Error'.split(' '), function(i, name){
    class2type['[object ' + name + ']'] = name.toLowerCase();
});
原文地址:https://www.cnblogs.com/easonw/p/11505304.html