Skip to content

js深拷贝 #30

@itboos

Description

@itboos

先附上结论:

 Object.assign(),  Array的 slice  concat 方法  对于引用类型数据都是浅拷贝
 JSON.strigify  JSON.parse 是深拷贝

此段代码来自

JSON.strigify和JSON.parse 🌰

    
    // 例1
    var source = { name:"source", child:{ name:"child" } } 
    var target = JSON.parse(JSON.stringify(source));
    target.name = "target";  //改变target的name属性
    console.log(source.name); //source 
    console.log(target.name); //target
    target.child.name = "target child"; //改变target的child 
    console.log(source.child.name); //child 
    console.log(target.child.name); //target child
    
    
    //例2
    var source = { name:function(){console.log(1);}, child:{ name:"child" } } 
    var target = JSON.parse(JSON.stringify(source));
    console.log(target.name); //undefined
    
    
    //例3
    var source = { name:function(){console.log(1);}, child:new RegExp("e") }
    var target = JSON.parse(JSON.stringify(source));
    console.log(target.name); //undefined
    console.log(target.child); //Object {}
    
    优点:
     /*
       * 1. 这两个方法是 ES5中引入的新的类型(支持的浏览器为IE8+) 兼容性较好
       * 2. 使用起来简单
       * 3. 可以满足基本的深拷贝需求,而且能够处理JSON格式能表示的所有数据类型
      */
    
     缺点:
      /*
       * 1. 不能拷贝方法,会直接忽略属性为方法的属性
       * 2. 不能拷贝正则,正则属性会变成一个空对象
       * 3. 如果元素是一个对象,则拷贝后此对象的__proto__ 上的constructor 属性会丢失,
       *  会变成 Object
       * 4. 无法处理对象存在循环引用的情况(JSON.parse方法对于存在循环引用的对象会报错,不能正确准换)
      */

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions