This is the 24th day of my participation in the August Genwen Challenge.More challenges in August

Copy the object

One of the most common problems for JavaScript beginners is how to copy an object. It looks like there should be a built-in copy() method. However, things are not as simple as they should be, because there is no way to choose a default replication algorithm. Such as:

    function anotherFunction(){
        console.log("juejin");
    }
    var anotherObject = {
        c:true
    };
    var anotherArray = [1.2];
    var myObject = {
        a:2.b:anotherObject,
        c:anotherArray,
        d:anotherFunction
    };
    anotherArray.push(anotherObject,myObject);
Copy the code

To accurately represent a copy of myObject, first determine whether it is a shallow copy or a deep copy. For shallow copies, the value of A in the copied new object copies the value of A in the old object, which is 2. However, the attributes B, C, and D in the new object are just three references, which are the same as the objects referenced by b, C, and D in the old object. For deep copy, anotherObject and anotherArray are copied in addition to myObject. AnotherArray refers to anotherObject and myObject, so you need to copy myObject again. This will cause an infinite loop due to circular references. Should the nesting dolls be tested and the cycle terminated? Or just report an error?

Aside from the nesting doll problem, we’re not sure what it means to “copy” a function. Some people serialize the source code of a function through toString(), but the result of this operation depends entirely on the implementation of JavaScript, and different engines handle different types of functions differently.

For jSON-safe objects, there is a clever way: (ps: JSON-safe means that you can serialize to a JSON string and parse out an object with exactly the same structure and value from that string)

    var newObj = JSON.parse(JSON.stringify(someObj));
Copy the code

However, this approach must ensure that the object is JSON-safe, so it only works in partial cases.

Shallow copies are much easier to understand and have fewer problems than deep copies, so ES6 defines the object.assign () method to implement shallow copies. The object.assign () method takes the first argument to a target Object, which can be followed by one or more source objects. It facilitates enumerable free keys from all source objects, copies them (assigned using the = operator) to the target object, and returns the target object.