第188天:extend拷贝创建对象的原理
一、拷贝创建对象的原理
1 //拷贝创建对象核心代码 2 function extend(target,source) { 3 //遍历对象 4 for(var i in source){ 5 target[i] = source[i]; 6 } 7 return target; 8 } 9 10 //游戏随机生成名字 11 var boy = { 12 name:'无忌' 13 ,image:'男性头像' 14 ,age:20 15 ,sex:'男' 16 }; 17 18 var gril = { 19 name:'风晴雪' 20 ,age:18 21 ,image:'女性头像' 22 ,sex:'女' 23 }; 24 25 26 var zuixiake = extend({}, boy); 27 zuixiake.name='醉侠客'; 28 console.log(zuixiake.name);//醉侠客 29 console.log(zuixiake.sex);//男
二、拷贝进阶用法
1 <script> 2 3 //extend2实现的功能:extend(target,obj1,obj2,obj3) 4 5 function extend () { 6 var key,i = 0,len = arguments.length,target = null,copy; 7 if(len === 0){ 8 return; 9 }else if(len === 1){ 10 target = this; 11 }else{ 12 i++; 13 target = arguments[0]; 14 } 15 for(; i < len; i++){ 16 for(key in arguments[i]){ 17 copy = arguments[i][key]; 18 target[key] = copy; 19 } 20 } 21 return target; 22 } 23 24 function extend2(){ 25 for (var p in source) { 26 if (source.hasOwnProperty(p)) { 27 target[p] = source[p]; 28 } 29 } 30 31 return target; 32 } 33 34 //游戏随机生成名字 35 var boy = { 36 name:'无忌' 37 ,image:'男性头像' 38 ,age:20 39 ,sex:'男' 40 }; 41 42 //技能名称,等级,伤害值,需要的魔法 43 var technology = {tname:'亡灵复活',tlevel:10,tstrength:3000,tmagic:30}; 44 45 var shenqi = {sname:'霜之哀伤',slevel:30,sstrength:3000}; 46 //当这个人有了穿上盔甲,圣衣,六神合体,戴上魔法戒指之后,自动也拥有一个技能 47 48 //第一种用法 49 var zuixiake = extend({}, technology,shenqi); 50 zuixiake.name='醉侠客'; 51 console.log(zuixiake.name);//醉侠客 52 console.log(zuixiake.tname);//亡灵复活 53 console.log(zuixiake.sname);//霜之哀伤 54 55 56 //第二种用法 57 extend(boy,technology,shenqi); 58 console.log(boy.name);//无忌 59 console.log(boy.tname);//亡灵复活 60 console.log(boy.sname);//霜之哀伤 61 62 </script>