使用原生js实现复制对象及扩展
2017-03-08 本文已影响0人
_李雷
使用原生js实现复制对象,扩展对象,类似JQuery中的extend()方法
var obj1 = {
name:'xiaoli1',
age:20
};
var obj2 ={
name:'xiaoli2',
age:21,
speak:function(){
alert("hi,I am"+name);
}
};
var obj3={
age:22
}
//复制对象方法
function cloneObj(oldObj){
if(typeof(oldObj)!='object')
return oldObj;
if(typeof(oldObj==null))
return oldObj;
var newObj=Object();
for(var i in oldObj)
newObj[i]=cloneObj(oldObj[i]);
return newObj;
}
//扩展对象
function extendObj(){
var args = arguments; //将传递过来的参数数组赋值给args变量
if(args.length<2)
return;
var temp = cloneObj(args[0]);
for(var n=1;n<args.length;n++){
for(var i in args[n])
temp[i]=args[n][i];
}
return temp;
}
var obj=extendObj(obj1,obj2,obj3);
console.log(obj); //{ name: 'xiaoli2', age: 22, speak: [Function] }
console.log(obj1); //{ name: 'xiaoli2', age: 22, speak: [Function] }
console.log(obj2); //{ name: 'xiaoli2', age: 21, speak: [Function] }
console.log(obj3); //{ age: 22 }