5.浅拷贝与深拷贝

时间:2022-01-21 19:55:14
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    <!--浅拷贝-->     ES6   Object.assign(...)方法实现了浅拷贝
// 要小心处理引用拷贝---对象类型(对象 函数 数组)拷贝就是引用拷贝 改变子类 就会改变父类  function extendCopy(p) {
        var c = {};
        for(var i in p){
            c[i] = p[i];
        }
        c.uber = p;
        return c;
    }
    var shape = {
        name:'shape',
        toString:function () {
            return this.name;
        }
    }
    var twoDee = extendCopy(shape);
    twoDee.name = '2D shape';
    twoDee.toString = function () {
        return this.uber.toString() + ','+ this.name;
    };

    var triangle = extendCopy(twoDee);
    triangle.name = 'Triangle';
    triangle.getArea = function () {
        return this.side * this.height/2;
    };
    triangle.side = 5;
    triangle.height = 10;
    triangle.getArea();       //输出 2 5  triangle.toString();      //输出 “shape, 2D shape,Triangle”  // 深拷贝 解决了浅拷贝拷贝引用的问题  function deepCopy(p,c) {
        var c = c || {};
        for(var i in p){
            if(typeof p[i] === 'object'){
                c[i] = (p[i].constructor === Array) ? [] : {};
                deepCopy(p[i],c[i]);
            }else{
                c[i] = p[i];
            }
        }
        return c;
    }
    var parent = {
        numbers:[1,2,3],
        letters:['a','b','c'],
        obj:{
            prop:1
        },
        bool:true  };

    var mydeep = deepCopy(parent);
    var myshallow = extendCopy(parent);
    mydeep.numbers.push(4,5,6);       //输出 6  mydeep.numbers;                   //输出 [1,2,3,4,5,6]  parent.numbers;                   // [1,2,3]  myshallow.numbers.push(10);       // 4  myshallow.numbers;                //[1,2,3,10]  parent.numbers;                   //[1,2,3,10]  mydeep.numbers;                   //[1,2,3,4,5,6] </script>
</body>
</html>