Before we talk about the depth of the first copies of the object to chat
What is an object?
Objects used to store key-value pairs and more complex entities, you can brace {…}
contains some optional and which attributes to create. Property is a key-value pair, the key is a string (also called property name), the value may be any type.
Objects and other primitive types are a very important difference compared to stored objects are copied by reference.
let user = { name: 'John' }; let admin = user; admin.name = 'Pete'; // change the reference of "admin" alert(user.name); // 'Pete', changes are seen from the "user" reference
The above example shows there is only one object, like a drawer with two of our key, if a key ( admin
) to use the drawer, use another key later ( user
) is open, you will see a change .
Another copy of an object variable is also equivalent to the creation of this object.
So how are we to copy an object it? Create a separate copy, a copy?
It is also possible, but a bit trickier, because JS does not support native methods to do so. In fact, we rarely do so. Copy the reference is often useful.
If we really want to do, you need to create a new object, traversing the properties of existing objects, copied to the new object in a state of original value.
like this:
let user = { name: "John", age: 30 }; let clone = {}; // new empty object // copy all property values for (let key in user) { clone[key] = user[key]; } // Now copy is a copy of the independent clone.name = "Pete"; // change the value of alert (user.name); // original object property value remains unchanged
We can also use Object.assign to achieve.
like this:
let user = { name: "John", age: 30 }; let clone = Object.assign({}, user);
It copied user
all of the properties of the object to an empty object, and then returns the copy of the object. In fact, this is the same with the assignment cycle, but shorter.
Until now, we assume that all user
properties are the original value, but if the object attribute points to object?
like this:
let user = { name: "John", sizes: { height: 182, width: 50 } }; let clone = Object.assign({}, user); alert (user.sizes === clone.sizes); // true, the same object // user share sizes and clone objects user.sizes.width ++; // here to change the value of a property alert (clone.sizes.width); // 51, here in the attribute value
This is called a shallow copy, in order to solve the above problems, and when we copy should check user[key]
each value, if an object is, we'll copy it again this object, this is called a deep copy.
There is a standard deep-copy algorithm to solve the above and some of the more complex cases, called Structured Cloning algorithm . In order not to repeat create the wheel, we use it in a library JS achieve lodash , the method name is called _.cloneDeep (obj) .