天天看點

js 克隆

js 如何克隆一個對象呢?

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;  

        }  

 測試代碼:

js 克隆

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";  

target2.say();  

 運作結果:

whut

hello,whuang

參考:

http://blog.csdn.net/zhaopei1125/article/details/6519680

繼續閱讀