Javascript: 深淺克隆;

一、深度克隆:javascript

Object.prototype.num = 1;
        var person1 = {
            name: '麗麗',
            age: 28,
            weight: 55,
            height: 168,
            sex: 'female',
            children:{
                first:{
                    name: '佳佳',
                    age: 9,
                    grade: '4年級'
                },
                second:{
                    name: '小剛',
                    age: 7,
                    grade: '三年級'
                },
                third:{
                    name: '小紅',
                    age: 6,
                    grade: '二年級'
                }
            },
            arr: []
        }
        var person2 = {};

        deepClone(person1,person2);
        person2.name = '瀟瀟';
        person2.arr = ['benz','red'];
        person2.children.forth = {
            name: '曉麗',
            age: 5,
            grade: '一年級'

        }
        console.log(person1,person2);

        function deepClone(origin,target){
            var target = target || {};
            var toStr = Object.prototype.toString;
            var arrType = '[object Array]';

            for(var key in origin){
                if(origin.hasOwnProperty(key)){
                    if(typeof(origin[key]) === 'object' && origin[key]!== null){
                        if(toString.call(origin[key]) === arrType){
                            target[key] = [];
                        }else{
                            target[key] = {};
                        }
                        deepClone(origin[key],target[key]);
                    }else{
                        target[key] = origin[key];
                    }
                }
            }
            return target;
        }

能夠對內部引用進行克隆,不會繼承原型上的東西java

相關文章
相關標籤/搜索