欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js 克隆 博客分类: javascript 克隆clone复制对象 

程序员文章站 2024-03-26 12:12:23
...

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