js 如何克隆一个对象呢?
- var clone = function(src){
- var target = {};
- for(var i in src){
- if(typeof src[i]==='object'){
- target[i] = arguments.callee(src[i]);
- }else{
- target[i] = src[i];
- }
- }
- return target;
- }
测试代码:
- var obj2={name:"whuang",age:27,say:function(){console.log("Hello,"+this.name)}};
- var obj3={school:"whut"};
- obj2.sch=obj3;
- var target2=clone(obj2);
- console.log(target2.sch.school);
- obj2.sch.school="ccc";
- console.log(target2.sch.school);
- target2.say();
运行结果:
whut
whut
Hello,whuang
参考:
http://blog.csdn.net/zhaopei1125/article/details/6519680