1: Pre-skill
Common data type: Number string Boolean Undefined null
Reference data type: obj
2: deep copy and shallow copy
Shallow copy: Creates a new object with an exact copy of the original object’s property values. If the property is of a primitive type, the value of the primitive type is copied. If the property is a reference type, the memory address is copied, and if one object changes the address, the other object will be affected
Deep copy: Copy an object completely out of memory and put it into a new area of memory. Modification of the new object does not affect the original object
3: the assignment
Assignment: When you assign an object to a new variable, you assign the object’s address on the stack, not the heap. That is, two objects point to the same space, and any object that changes has changed the contents of the storage space. So the two objects are associated.
So assignment is your dad making a copy of a key in the house and giving it to you
var sb = {
name: 'two dogs'.hobby: ['learning'['Go to the movies'.'shopping'].'running']}var sb1 = sb
sb1.name = 'iron eggs'
sb1.hobby[0] = 'Play games'
console.log(sb);
console.log(sb1);
Copy the code
Shallow copy: Creates a new memory space in the heap. Before and after the copy, the basic data types do not affect each other, but the object reference resource sharing memory before and after the copy affects each other
Your father gave you a copy of the house key, but he won’t give you the key to your father’s safe. Do you understand
var sb = {
name: 'two dogs'.hobby: ['learning'['Go to the movies'.'shopping'].'running']}function dd(sb) {
var target = {}
for (var i in sb) {
if (sb.hasOwnProperty(i)) {
target[i]=sb[i]
}
}
return target
}
var sb1 = dd(sb)
sb1.name = 'iron eggs'
sb1.hobby[0] = 'Play games'
console.log(sb);
console.log(sb1);
Copy the code
Deep copy: Creates a new area in the heap to store new objects, and makes a recursive copy of sub-objects
Your dad gave you the keys to the house and the safe, and he told you to go out on your own
// Recursive operation
var sb = {
name: 'two dogs'.hobby: ['learning'['Go to the movies'.'shopping'].'running']}function deep(sb) {
var target = new sb.constructor()
if(typeofsb! = ='object')return sb
for (var i in sb) {
if (sb.hasOwnProperty(i)) {
target[i] = deep(sb[i])
}
}
return target
}
//var sb1 = deep(sb)
var sb1 = JSON.parse(JSON.stringify(sb))
sb1.name = 'iron eggs'
sb1.hobby[0] = 'Play games'
console.log(sb);
console.log(sb1);
Copy the code