zoukankan      html  css  js  c++  java
  • 深拷贝,浅拷贝

    js

    深拷贝:

    function deepCopy(o){
        return JSON.parse(JSON.stringify(o));
    }
    var a = {a:1,b:2,c:3};
    var b = deepCopy(a);
    b.a = 4;
    alert(a.a); //1        
    alert(b.a); //4

    这种方式很好理解,对一个Object对象而言,先使用内置的JSON.stringify()函数,将其转化为数组。此时生成的字符串已经和原对象没有任何联系了,再通过JSON.parse()函数,将生成的字符串转化为一个新的对象。它只能对Object对象实现深拷贝,对于Function等对象,JSON.stringify()函数会直接返回undefined。

    Object中包涵Function类型,这种对象的深拷贝

    function getType(o){
        return ((_t = typeof(o)) == "object" ? o==null && "null" || Object.prototype.toString.call(o).slice(8,-1):_t).toLowerCase();
    }
    function extend(destination,source){
        for(var p in source){
            if(getType(source[p])=="array"||getType(source[p])=="object"){
                destination[p]=getType(source[p])=="array"?[]:{};
                arguments.callee(destination[p],source[p]);
            }else{
                destination[p]=source[p];
            }
        }
    }
    var test={a:"ss",b:[1,2,3],c:{d:"css",e:"cdd"}};
    var test1={};
    extend(test1,test);
    test1.b[0]="change"; //改变test1的c属性对象的d属性
    alert(test.b[0]);  //不影响test,返回1
    alert(test1.b[0]); //返回change

    .net中的深拷贝和浅拷贝:ICloneable接口实现

    浅拷贝拷贝:

     

    深拷贝实现:

    使用流的方式拷贝出去

    参考:http://book.51cto.com/art/201109/292343.htm

  • 相关阅读:
    IOC / AOP
    Volatile
    观察者模式
    Gang Of Four的23中设计模式
    适配器模式
    享元模式
    设计模式
    B树和B+树
    Java内存模型(JMM)
    【Java的IO流之文件字符输入输出流 25】
  • 原文地址:https://www.cnblogs.com/wanglao/p/3598207.html
Copyright © 2011-2022 走看看