對jQuery.isArray方法的分析


jQuery.isArray方法應於判斷是不是數組,是的話返回true,否則返回false。調用如:jQuery.isArray([]),返回true。其實現源碼如下:

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

我們看到它的主要邏輯是先看瀏覽器支不支持Array.isArray方法,如果不支持則調應jQuery自己的jQuery.type方法,看其返回值是不是"array"。

firefox、chrome、IE9及以上的瀏覽器都支持Array.isArray方法。其它瀏覽器就需要jQuery.type的幫忙了,jQuery.type的源碼如下:

type: function( obj ) {
    if ( obj == null ) {
        return obj + "";
    }
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[ toString.call(obj) ] || "object" :
        typeof obj;
}

代碼中的if好理解,如果傳入的null則返回“null”字符串。

return 后面的代碼結構上看起來比較亂。我們整理如下:

return ( typeof obj === "object" || typeof obj === "function" )  ? ( class2type[ toString.call(obj) ] || "object" ) : typeof obj;

現在清楚多了,它是判斷( typeof obj === "object" || typeof obj === "function" )的值是不是真,如果是真則返回 ( class2type[ toString.call(obj) ] || "object" ),反之則返回 typeof obj。

所以當傳入的是字符串,數字,undefined的時直接返回 typeof obj。當傳入的是對象、數組、函數時則直接返回 ( class2type[ toString.call(obj) ] || "object" )。現在主要看看class2type[ toString.call(obj) ]的實現:

var class2type = {};
var toString = class2type.toString;
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

jQuery定義了class2type的一個對象,並將其初始化為如下的格式:

{
    "[object Array]" : "array",
    "[object Boolean]" : "boolean",
    "[object Date]" : "date",
    "[object Error]" : "error",
    "[object Function]" : "function",
    "[object Number]" : "number",
    "[object Object]" : "object",
    "[object RegExp]" : "regexp",
    "[object String]" : "string"
}

toString方法的返回值正好是class2type對象的key值。所以class2type[ toString.call(obj) ]正好得到我們需要的返回類型字符串。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM