一.首先定义个person类
var person = {
eat:function(){
console.log("person:吃顿饭")
},
chirldren:["小马","小明","小红"],
name:"",
sex:function(x){
return x?"男":"女";
},
data:new Date(),
money:null,
laopo:undefined
}
二.声名克隆函数
function clone(object){
if(object == null) return null;
if(typeof object !== 'object') return object;//!== 类型相同才判断
if(object.constructor == Date) return new Date(object);//日期
if(object.constructor == 'RegExp') return new RegExp(object)//正则
var newObject = new object.constructor();
console.log(arguments)
for (var key in object) {
if(object.hasOwnProperty(key)){
var val = object[key];
//如果key为 'object' 就在调用一下克隆方法
newObject[key] = typeof val === 'object' ? arguments.callee(val):val;
}
}
return newObject;
}
三.打印一下看看~
var zhangsan = clone(person);
console.log(zhangsan)
打印结果