jQuery 원본 연구 분석 학습 노트 - 정적 방법과 속성(10)

26039 단어 jQuery원본 연구
jQuery 원본에서 몇 가지 중요한 정적 속성과 방법을 정의했는데 이것은 다른 모듈이 실현하는 기초이고 전체적인 원본 구조는 다음과 같다.
    // window.jQuery winow.$       _jQuery _$
    _jQuery = window.jQuery,

    // Map over the $ in case of overwrite
    _$ = window.$,
jQuery.extend({
    //   JavaScript     $         ,jQuery    。  jQuery  ,$     jQuery    ,        $          。         jQuery       JavaScript  ,         $.noConflict()         :
    noConflict: function( deep ) {
    // window.$ ===jQuery,   window.$        _$.
    //     jQuery       $    ,    $        javascript 
        if ( window.$ === jQuery ) {
            window.$ = _$;
        }

        // deep true, window.jQuery===jQuery,   window.jQuery        _jQuery
        if ( deep && window.jQuery === jQuery ) {
            window.jQuery = _jQuery;
        }

        return jQuery;
    },

    // Is the DOM ready to be used? Set to true once it occurs.
    isReady: false,

    // A counter to track how many items to wait for before
    // the ready event fires. See #6781
    readyWait: 1,

    //               

    isFunction: function( obj ) {
        return jQuery.type(obj) === "function";
    },

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

    isWindow: function( obj ) {
        return obj != null && obj == obj.window;
    },

    isNumeric: function( obj ) {
        return !isNaN( parseFloat(obj) ) && isFinite( obj );
    },

    //         Javascript  ,     undefined null,  "undefined" "null";     Js    ,           ;        "object"
    type: function( obj ) {
        return obj == null ?
            String( obj ) :
            //toString = Object.prototype.toString
            //  Object     toString()  obj      ,       [object class],   class      ,Object.prototype.toString.call(new Date())  [object Date]
            class2type[ toString.call(obj) ] || "object";
    },
    //            ”  “   ,        {}  new Object()     
    isPlainObject: function( obj ) {
        //obj     false,Object.prototype.toString.call(obj)     [object object ],obj DOM  ,obj window  ,       false
        if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
            return false;
        }

        try {
            //     obj       Object()  ,
              obj    constuctor,               constructor  ,             ,    obj    constructor,                {}    
            if ( obj.constructor &&
                //hasOwn = Object.prototype.hasOwnProperty
                !hasOwn.call(obj, "constructor") &&
                !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
                return false;
            }
        } catch ( e ) {
            // IE8,9 Will throw exceptions on certain host objects #9897
            return false;
        }

        //     obj            ,      ,            ,   true

        var key;
        for ( key in obj ) {}

        return key === undefined || hasOwn.call( obj, key );
    },

    //           (     )
    isEmptyObject: function( obj ) {

        //for-in                       ,   ,   false,      true
        for ( var name in obj ) {
            return false;
        }
        return true;
    },

    //       ,              
    error: function( msg ) {
        throw new Error( msg );
    },

    //   json   ,    javascript  ,        json           
    parseJSON: function( data ) {

        //       ,       、null、undefined,   null
        if ( typeof data !== "string" || !data ) {
            return null;
        }

        //            ,  IE6/7
        data = jQuery.trim( data );

        //    ,       JSON.parse()  JSON   ,   
        if ( window.JSON && window.JSON.parse ) {

            //JSON.parse() JSON.stringify(),  JSON    javaScript         
            //JSON.parse()  JSON    JSON  ,JSON.stringify()  JSON   JSON   
            return window.JSON.parse( data );
        }

        //     JSON.parse(),          ,
        // rvalidchars = /^[\],:{}\s]*$/,
        // rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
    // rvalidtokens = /"[^"\\
\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
// rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // xml , XML parseXML: function( data ) { if ( typeof data !== "string" || !data ) { return null; } var xml, tmp; try { if ( window.DOMParser ) { //IE9+ tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, // , , , , jQuery.noop() noop: function() {}, // javaScript globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // execScript() , Jscirpt, // execScript(), execScript(data); , ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // , CSS // rdashAlpha = /-([a-z]|[0-9])/ig, // rmsPrefix = /^-ms-/, camelCase: function( string ) { // rmsPrefix "-ms-", "ms-", rdashAlpha "-" , replace() fcamelCase() return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, // DOM , , nodeName: function( elem, name ) { // elem.nodeName name , elem.nodeName.toUpperCase() elem.nodeName , elem dom , elem nodeName return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { // ... }, // //rnotwhite = /\S/, // trimLeft = /^\s+/, // trimRight = /\s+$/, // trim = String.prototype.trim trim: trim ? function( text ) { // null undefined, // String.prototype.trim() return text == null ? "" : trim.call( text ); } : // , toString() text , trimLeft trimRight function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // // array: , //results: jQuery , results, makeArray: function( array, results ) { var ret = results || []; // if ( array != null ) { var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { //array ,array ,array , window , , array // push.call(ret,array), ret 。 array, ret , ret, ret push.call( ret, array ); } else { // array , jQuery.merge() ret jQuery.merge( ret, array ); } } return ret; }, // // elem: //array: , , value //i: , 0 inArray: function( elem, array, i ) { var len; if ( array ) { // indexOf(), if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; // i, i, 0, 0, , ,Math.max() 0 len+i , len+i 0, i 0 i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; }, // , //first: , length //second: 、 , first merge: function( first, second ) { var i = first.length, j = 0; // second length if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { //second length, , undefined first while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } // first length first.length = i; return first; // first }, // , //array: //callback: , : , grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // , , inv true, false ret , // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { // }, // , jQuery , guid: 1, // , proxy: function( fn, context ) { // context , jQuery.proxy(context,name), jQuery.proxy(fn,context) if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // fn , undefined if ( !jQuery.isFunction( fn ) ) { return undefined; } // , slice() var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // guid, , proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; // return proxy; }, // now: function() { return ( new Date() ).getTime(); }, // uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} })
//   class2type
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

함수 fcamelCase()는 하이픈 문자를 대문자로 변환하고 반환합니다.
fcamelCase = function( all, letter ) {
        return ( letter + "" ).toUpperCase();
    }

좋은 웹페이지 즐겨찾기