结构-行为-样式-Javascript 深度克隆函数(转)

突然想到有一回面试的时候有一个问题一直挂在心头,于是乎在网上找了找,这个比较好:

 

//深度克隆
        function deepClone(obj) {
            var result, oClass = isClass(obj);
            //确定result的类型
            if (oClass === "Object") {
                result = {};
            }else if (oClass === "Array") {
                result = [];
            }else {
                return obj;
            }
            for (key in obj) {
                var copy = obj[key];
                if (isClass(copy) == "Object") {
                    result[key] = arguments.callee(copy); //递归调用
                }
                else if (isClass(copy) == "Array") {
                    result[key] = arguments.callee(copy);
                }
                else {
                    result[key] = obj[key];
                }
            }
            return result;
        }
        //返回传递给他的任意对象的类
        function isClass(o) {
            if (o === null) return "Null";
            if (o === undefined) return "Undefined";
            //从第九位开始截取
            return Object.prototype.toString.call(o).slice(8, -1);
        }
        var oPerson = {
            oName: "rookiebob",
            oAge: "18", 
            oAddress: {province: "beijing"}, 
            ofavorite: ["swimming", {reading: "history book"}], 
            skill: function () {console.log("bob is coding");}
        };
        //深度克隆一个对象
        var oNew = deepClone(oPerson);
        console.log(oNew);

 

本代码转自:深度克隆函数

 

posted @ 2016-09-07 15:58  ChickenTang  阅读(129)  评论(0编辑  收藏  举报