学习jquery源代码---$.extend

xiaoxiao2021-02-27  234

/** * 注:源代码段落拷贝自jquery v1.12.3,中文注释是本人自行添加,如有疏漏,还望前辈们批评指正 * * 分析一下这个函数的主要功能如下: * * 调用方式1:version added: 1.0 * jQuery.extend( target [, object1 ] [, objectN ] ) * 将object1 到 objectN全部合并到target对象 * * 调用方式2:version added: 1.1.4 * deep参数可选,表示是否支持深拷贝 * 将object1 到 objectN全部合并到target对象 * jQuery.extend( [deep ], target, object1 [, objectN ] ) */ // 从这里看出jquery.extend和jquery.fn.extend是同一个匿名函数 jQuery.extend =jQuery.fn.extend =function() { var src,copyIsArray, copy,name, options,clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // 默认不支持deep,需要显式传入该属性 // Handle a deep copy situation if ( typeoftarget === "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 ( typeoftarget !== "object" && !jQuery.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 ) { // 目标属性值 src = target[ name ]; // 选项属性值 copy = options[ name ]; // 如果存在一个对象拥有一个属性是自身,则拷贝就会陷入死循环,因此需要跳过那个属性的拷贝 // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays // 如果支持深拷贝,并且属性是一个对象或者数组 if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = jQuery.isArray( copy ) ) ) ) { // 不是利用标识判断是否是数组,如果不是数组,则是对象 if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src ) ? src : []; } else { clone = src && jQuery.isPlainObject(src ) ? src : {}; } // 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; };
转载请注明原文地址: https://www.6miu.com/read-8698.html

最新回复(0)