$.type 怎么精确判断对象类型的 --(源码学习2)

目标: 

var a = [1,2,3];
    console.log(typeof a); //->object
    console.log($.type(a)); //->array
 
jQuery -v1.12.4
 1 jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
 2 function( i, name ) {
 3     class2type[ "[object " + name + "]" ] = name.toLowerCase();
 4 } );
 5 
 6 
 7 
 8 ....
 9 
10 
11 type: function( obj ) {
12         if ( obj == null ) {
13             return obj + "";
14         }
15         return typeof obj === "object" || typeof obj === "function" ?
16             class2type[ toString.call( obj ) ] || "object" :
17             typeof obj;
18     },

分析:

第1-4行:通过遍历给class2type对象添加属性

    

第16行:通过toString.call(obj)来得到obj的属性。

原文地址:https://www.cnblogs.com/zqzjs/p/5557204.html