In-depth understanding of the fourth part of the javascript object series - object copy

previous words

Object copy is divided into shallow copy (shallow) and deep copy (deep). Shallow copy only copies the properties of one layer of objects, and does not perform recursive copying, and when javascript stores objects, it only stores the address of the object. So a shallow copy will result in subobjects in the object pointing to the same memory address (modifying one object affects the other). The deep copy is different, it not only copies the properties of the original object one by one. Moreover, the objects contained in each attribute on the original object are also recursively copied to the new object by the deep copy method, and all levels are copied.

1. Shallow copy

[Method 1]: Simple copy
Create a new empty object, and use a for-inloop to copy all the properties of the object to the newly created empty object.

function simpleClone1(obj) {
        if(typeof obj != "object") {
            //如果传的不是一个对象,则直接退出
            return false;
        }

        var cloneObj = {};
        for(var i in obj)  {
            cloneObj[i] = obj[i];
        }
        return cloneObj;
    }

   var obj1={a:1,b:2,c:[1,2,3]};
   var obj2=simpleClone1(obj1);
   console.log(obj1.c); //[1,2,3]
   console.log(obj2.c); //[1,2,3]
   obj2.c.push(4);
   console.log(obj2.c); //[1,2,3,4]
   console.log(obj1.c); //[1,2,3,4]

[Method 2]: Use the attribute descriptor to create an empty instance object
through the prototype of the object. Through the forEach statement, the attribute descriptors of all attributes of the object are obtained, and they are set as parameters to the newly created empty instance object.

function simpleClone2(origObj) {
        //利用传入对象的原型创建一个空对象,这个新对象和原对象指向同一个原型
        var copy = Object.create(Object.getPrototypeOf(origObj));
        //遍历原始对象的所有属性名
        Object.getOwnPropertyNames(origObj).forEach(function(propKey) {
            //得到原始对象属性的属性描述符
            var desc = Object.getOwnPropertyDescriptor(origObj,propKey);
            //把这些属性和对应的属性描述符重新定义到待赋值的空对象上
            Object.defineProperty(copy,propKey,desc);
        });
        return copy;
    }

   var obj1={a:1,b:2,c:[1,2,3]};
   var obj2=simpleClone1(obj1);
   console.log(obj1.c); //[1,2,3]
   console.log(obj2.c); //[1,2,3]
   obj2.c.push(4);
   console.log(obj2.c); //[1,2,3,4]
   console.log(obj1.c); //[1,2,3,4]

[Method 3]: Use the extend() method of jquery.

var obj1={a:1,b:2,c:[1,2,3]};
var obj2=$.extend({},obj1);
console.log(obj1.c); //[1,2,3]
console.log(obj2.c); //[1,2,3]
obj2.c.push(4);
console.log(obj2.c); //[1,2,3,4]
console.log(obj1.c); //[1,2,3,4]

2. Deep copy

[Method 1]: Traverse and copy When
copying the properties of an object, judge it, if it is an array or an object, call the copy function again; otherwise, copy the object properties directly.

function deepClone1(obj,cloneObj) {
        if(typeof obj != "object") {
             return false;
        }
        var cloneObj = cloneObj || {};

        for(var i in obj) {
            //如果是对象的子对象,则递归复制
            if(typeof obj[i] === "object") {
                //判断该构造函数(Array)的原型是否存在于该对象(obj[i])的原型链上
                cloneObj[i] = (obj[i] instanceof Array)? []:{};
                //递归复制
                arguments.callee(obj[i],cloneObj[i]);
            } else {
                cloneObj[i] = obj[i];
            }
        }
        return cloneObj;
    }

   var obj1={a:1,b:2,c:[1,2,3]};
   var obj2=deepClone1(obj1);
   console.log(obj1.c); //[1,2,3]
   console.log(obj2.c); //[1,2,3]
   obj2.c.push(4);
   console.log(obj2.c); //[1,2,3,4]
   console.log(obj1.c); //[1,2,3]

[Method 2]: JSON
uses the parse and stringify methods of the JSON global object to implement deep copying. Represented data structure.

function jsonClone(obj){
       return JSON.parse(JSON.stringify(obj));
       //把传入的对象初始化一个字符串,在以这个字符串为依据创建一个新的对象,
       // 之所以会实现深拷贝,是因为这个对象是以传入的原对象为基础的,
       // 它们在不同的内存空间中,所以操作一个不会影响另一个。
   }
   var obj1={a:1,b:2,c:[1,2,3]};
   var obj2=jsonClone(obj1);
   console.log(obj1.c); //[1,2,3]
   console.log(obj2.c); //[1,2,3]
   obj2.c.push(4);
   console.log(obj2.c); //[1,2,3,4]
   console.log(obj1.c); //[1,2,3]

[Method 3]: Use the extend() method of jquery.

var obj1={a:1,b:2,c:[1,2,3]};
var obj2=$.extend(true,{},obj1);
console.log(obj1.c); //[1,2,3]
console.log(obj2.c); //[1,2,3]
obj2.c.push(4);
console.log(obj2.c); //[1,2,3,4]
console.log(obj1.c); //[1,2,3]

Reprinted from: Little Match's Blue Ideal
http://www.cnblogs.com/xiaohuochai/p/5613593.html
When reading the teacher's blog, I treat it as a book, so most of my blogs come from the teacher's blog The original words and examples, plus some of my own understanding, and made appropriate annotations, and some tests on the teacher's code.

Article label: In-depth understanding of javascript functions series 6 - higher-order functions

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325663931&siteId=291194637