javascript深拷贝的实现

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<script>
    function type(obj) {
        var toString = Object.prototype.toString;
        var map = {
            '[object Boolean]' : 'boolean',
            '[object Number]'  : 'number',
            '[object String]'  : 'string',
            '[object Function]' : 'function',
            '[object Array]'  : 'array',
            '[object Date]'   : 'date',
            '[object RegExp]'  : 'regExp',
            '[object Undefined]': 'undefined',
            '[object Null]'   : 'null',
            '[object Object]'  : 'object'
        };
        return map[toString.call(obj)];
    }

    function deepClone(data) {
        var t = type(data), o, i, ni;

        if(t === 'array') {
            o = [];
        }else if( t === 'object') {
            o = {};
        }else {
            return data;
        }

        if(t === 'array') {
            for (i = 0, ni = data.length; i < ni; i++) {
                o.push(deepClone(data[i]));
            }
            return o;
        }else if( t === 'object') {
            for( i in data) {
                o[i] = deepClone(data[i]);
            }
            return o;
        }
    }

    var test = {
        a: 'a',
        b: 'b'
    };

    var test2 = test;
    test2.a = 'a2';
    console.log(test.a === 'a2');  //true

    //深拷贝
    var test3 = deepClone(test);
    test3.b = 'b2';
    console.log(test.b === 'b2');  //false

    //使用jQuery做深拷贝
    var myTest = {
        a: 'a',
        b: 'b'
    };
    var myTest2 = jQuery.extend({}, myTest);
    myTest2.b = 'b2';
    console.log(myTest.b === 'b2');  //false

</script>
</body>
</html>

posted @ 2017-09-20 15:56  徐同保  阅读(105)  评论(0编辑  收藏  举报