1、淺拷貝 javascript
當咱們須要將一個對象拷貝至另外一個對象時,咱們通常會這麼實現java
function shadowCopy(source,target){ var target=target||{}; for(var i in source) { target[i]=source[i]; } return target; } var a={name:'Lily',age:19}; var b=shadowCopy(a);//b={name:'Lily',age:19}
淺拷貝的問題是,若是父對象的屬性等於數組或另外一個對象,實際上子對象得到的只是一個內存地址,而不是真正拷貝,父對象的數組或對象屬性發生變化時,子對象對應屬性也發生變化sql
function shadowCopy(source,target){ var target=target||{}; for(var i in source) { target[i]=source[i]; } return target; } var a={name:'Lily',Hobbies:['Music','Sport']}; var b=shadowCopy(a);//b={name:'Lily',Hobbies:['Music','Sport']} a.Hobbies.push('Read');//b={name:'Lily',Hobbies:['Music','Sport','Read']}
2、深拷貝 數組
爲了解決上述問題,須要對對象的數組和對象屬性進行深拷貝。它的實現並不難,只要遞歸調用"淺拷貝"就好了oop
function deepCopy(source,target){ var target=target||{}; for(var i in source) { if(typeof source[i] === 'object'){ target[i] = (source[i].constructor === Array ) ? [] : {} ; deepCopy(source[i],target[i]); }else{ target[i]=source[i]; } } return target; } var a={name:'Lily',Hobbies:['Music','Sport']}; var b=deepCopy(a);//b={name:'Lily',Hobbies:['Music','Sport']} a.Hobbies.push('Read');//b={name:'Lily',Hobbies:['Music','Sport','Read']},b={name:'Lily',Hobbies:['Music','Sport']}
上述代碼中有一個問題,當待拷貝對象中存在自引用時,程序會陷入無限循環源碼分析
var a={name:'lily'};
a.obj=a;
deepCopy(a);
在Chome Console運行時,以下提示
RangeError: Maximum call stack size exceeded
爲了解決自引用問題,拷貝時加入判斷邏輯this
function deepCopy(source,target){ var target=target||{}; for(var i in source) { //防止自引用 if(source[i] === source ) continue; if(typeof source[i] === 'object'){ target[i] = (source[i].constructor === Array ) ? [] : {} ; deepCopy(source[i],target[i]); }else{ target[i]=source[i]; } } return target; } var a={name:'lily'}; a.obj=a; var b=deepCopy(a);//b={name:'lily'}
3、JQuery拷貝實現 spa
網上有不少對JQuery extend方法的分析,有不瞭解的能夠去搜索閱讀 prototype
貼一處被分析的源碼對象
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { 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; };
4、JQuery實現疑問
在閱讀上述JQuery代碼時,有個地方有疑問,疑問代碼以下
// Prevent never-ending loop if ( target === copy ) { continue; }
注意到,在extend方法中,爲了防止無限循環,這裏有一個邏輯,在target對象等於copy對象時,調過此次複製操做。其中,copy對象爲options對象的屬性對象。
問題是,這裏爲何要拿target對象與copy對象比較呢?難道不該該是比較copy對象和options對象嗎?
帶着這個疑問,在一個已經引入了JQuery庫的頁面Console中執行下
var a={name:'lily'}; a.obj=a; var b={}; $.extend(true,b,a); RangeError: Maximum call stack size exceeded
能夠看到,當a對象中存在自引用屬性時,extend方法並不能防止無限循環的發生
那麼判斷target === copy能起到什麼做用呢?
var a={name:'lily'}; var b={age:19}; a.obj=b; $.extend(true,b,a); //此時b={age: 19, name: "lily"}
去掉判斷target === copy會陷入無限循環嗎?其實是不會的
var a={name:'lili'}; var b={age:19}; a.obj=b; deepCopy(true,b,a); //b=Object {age: 19, name: "lili", obj: Object} //其中Object爲b
這裏的deepCopy是我將JQuery的extend方法,去掉上述判斷邏輯,本身實現了一份
function deepCopy() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { 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 ( options === copy ) { continue; } */ // Recurse if we're merging plain objects or arrays if ( deep && copy && ( isPlainObject(copy) || (copyIsArray =isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] =deepCopy( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; var isString=function(obj){ return Object.prototype.toString.call(obj) === '[object String]'; }; var isArray=function(obj){ return Object.prototype.toString.call(obj) === '[object Array]'; }; var isPlainObject=function(obj){ return Object.prototype.toString.call(obj) === '[object Object]'; } var a={name:'lili'}; var b={age:19}; a.obj=b; deepCopy(true,b,a);
View Code
因此這裏, 是JQuery extend方法的實現bug,仍是個人理解有誤呢?
搜到的一些對JQuery extend方法的源碼分析,並無看到這個疑問,也挺奇怪的。