標籤:
$.extend(obj1,0bj2,{"name":"s","age":22})//target 要拷貝到哪個對象上// i 要執行拷貝的次數// length 要拷貝的參數的長度// name 對象參數中屬性值// options 對象參數// clone 深度拷貝時重名對象屬性的拷貝// target 要拓展的對象jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, // 常見用法 jQuery.extend( obj1, obj2 ),此時,target為arguments[0] i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { // 如果第一個參數為true,即 jQuery.extend( true, obj1, obj2 ); 的情況 deep = target; // 此時target是true target = arguments[1] || {}; // target改為 obj1 // skip the boolean and the target i = 2; } // 以上處理:如果第一個參數是boolean,第二個參數是target。 // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { // 如果target不是一個對象,設定預設對象。 target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { // 處理這種情況 jQuery.extend(obj),或 jQuery.fn.extend( obj ) target = this; // jQuery.extend時,this指的是jQuery;jQuery.fn.extend時,this指的是jQuery.fn --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[i]) != null ) { // 比如 jQuery.extend( , obj2, obj3, ojb4 ),options則為 obj2、obj3... // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { // 防止自引用:$.extend(x,{"name1":x});如果 如果target和option[name1]的值一樣,會迴圈迭代。 //看網上還有說應該要用src和copy比較的,$.extend({"name1":"張三","age":"14"},{"name1":"李四","age":"14"}),這兩個可以進行操作的。 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 { //被拷貝的屬性值是個plainObject,比如{ nick: ‘casper‘ } 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 ) { // 淺拷貝,且屬性值不為undefined target[ name ] = copy; } } } } // Return the modified object return target;{name1:"sdasd","name2":{name1:"sdasd","name2":{name1:"sdasd","name2":{name1:"sdasd","name2":{name1:"sdasd","name2":{name1:"sdasd","name2":{name1:"sdasd","name2":{name1:"sdasd","name2":}}}}}}}}
jquery extend源碼解析