Javascript初级 JavaScript进阶

JavaScript深度拷贝


示例代码


<html>

<head>

    <meta charset=”utf-8>

    <title></title>

</head>

<body>

<script type=”text/javascript”>

      Var o={};

      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 twodshape=extendcopy(shape);

Twodshape.name=’2d shape;

Twodshape.tostring=function(){

   Return this.uber.tostring()+”- -”+this.name;

}

Var triangle=extendcopy(twodshape);

Triangle.name=’triangle’;

Triangle.getarea=function(){

Return this.side*this.height/2;

}

Triangle.side=5;

Triangle.height=10;

Console.log(triangel.getarea());

 

Function deepcopy(p,y){

   Var c=c| |{};

   For(var i in p){

       If(typeof p[i]===’bject’){

          C[i]=(p[i].constructor===array)?[]:{};

          Deepcopy(p[i],c[i]);

       }else{

          C[i]=p[i];

       }

}

      Return c;

}

Var mydeep=deepcopy(parent);

Var myshallow=extendcopy(parent);

Mydeep.numbers.push(4,5,6);

Console.log(mydeep.numbers);

Console.log(parent.numbers);

 

Myshallow.numbers.push(7,8,9)

Console.log(myshallow.numbers);

Console.log(parent.numbers);

        </script>

</body>

</html>


执行结果


javascript1.png 



【本文由麦子学院独家原创,转载请注明出处并保留原文链接】

logo
© 2012-2016 www.maiziedu.com
蜀ICP备13014270号-4 Version 5.0.0 release20160127

免费领取价值1888元求职宝典!

客服热线 400-862-8862

回到顶部