直接上代码
function copy(obj){
//是对象进行递归拷贝
if (typeof obj ==='object' && obj!==null){
let Constructor=obj.constructor
if (Constructor===Date){
return new Date(obj.getTime())
}
if (Constructor===RegExp){
return new RegExp(obj)
}
let result=new Constructor()
for (let key in obj){
result[key]=copy(obj[key])
}
return result
}
//简单类型直接返回
return obj
}
测试:
let obj={
name:'zs',
age:10,
hobby:['抽烟','喝酒'],
test(){
console.log("我是函数")
},
time:new Date()
}
let c=copy(obj)
console.log(obj);
console.log(c);
c.hobby.push("女人")
console.log(obj);
console.log(c);
测试结果: