三、jQuery源码(3)------ 2020-04-05

2020-04-05  本文已影响0人  自己写了自己看

1、jquery.extend()

/**
* extend()方法是挂载到jQuery和jQuery原型上的方法:
* 我们可以通过下面两种方式调用:
* (1): $.extend();
* (2): $.fn.extend();
*/
jQuery.extend = jQuery.fn.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
        target = arguments[ 0 ] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;

        // Skip the boolean and the target
        target = arguments[ i ] || {};
        i++;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !isFunction( target ) ) {
        target = {};
    }

    // Extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }

    for ( ; i < length; i++ ) {

        // Only deal with non-null/undefined values
        if ( ( options = arguments[ i ] ) != null ) {

            // Extend the base object
            for ( name in options ) {
                copy = options[ name ];

                // Prevent Object.prototype pollution
                // Prevent never-ending loop
                if ( name === "__proto__" || target === copy ) {
                    continue;
                }

                // Recurse if we're merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
                    ( copyIsArray = Array.isArray( copy ) ) ) ) {
                    src = target[ name ];

                    // Ensure proper type for the source value
                    if ( copyIsArray && !Array.isArray( src ) ) {
                        clone = [];
                    } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
                        clone = {};
                    } else {
                        clone = src;
                    }
                    copyIsArray = false;

                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};

2、extend()方法两种调用方式的区别:

/**
* 1、通过 $.extend()调用是把jQuery当做一个普通对象来用,
*  是向jQuery这个普通对象身上扩展方法,这种用法一般是
*  为了完善类库,提供更多的工具方法;扩展到jQuery对象上;
*
* 2、通过$.fn.extend()调用是把jQuery当做构造函数来用,
*  这样用一般是为了写插件,让jQuery的实例来调用;
*  这时是扩展到jQuery构造函数的原型上;
*/


上一篇 下一篇

猜你喜欢

热点阅读