1. 程式人生 > >對象合並

對象合並

形式 func sta call ceo cti xtend eof instance

寫組件的時候經常會用到默認設置,而默認設置經常以對象形式傳參

//方法一 function objMerge(obj1, obj2) {   //var key;   for(key in obj2) {     // 如果target(也就是obj1[key])存在,且是對象的話再去調用deepMerge,     //否則就是obj1[key]裏面沒這個對象,需要與obj2[key]合並     obj1[key] = obj1[key] && obj1[key].toString() === "[object Object]" ?     deepMerge(obj1[key], obj2[key]) : obj1[key] = obj2[key];   }   return obj1; }; //方法二 function DeepExtend(obj1,obj2){   if(Object.prototype.toString.call(obj1) === ‘[object Object]‘ && Object.prototype.toString.call(obj2) === ‘[object Object]‘){     for( prop2 in obj2){//obj1無值,都有取obj2       if(!obj1[prop2]){         obj1[prop2] =obj2[prop2];       }else{//遞歸賦值         obj1[prop2]=DeepExtend(obj1[prop2],obj2[prop2]);       }     }   }else if(Object.prototype.toString.call(obj1) === ‘[object Array]‘ && Object.prototype.toString.call(obj2) === ‘[object Array]‘){     // 兩個都是數組,進行合並     obj1=obj1.concat(obj2);   }else{//其他情況,取obj2的值     obj1 = obj2;   }     return obj1; }; //方法三 function extend(des, src, override){   if(src instanceof Array){     for(var i = 0, len = src.length; i < len; i++)       extend(des, src[i], override);     }     for( var i in src){       if(override || !(i in des)){         des[i] = src[i];       }     }   return des; }

對象合並