As we know, both assign() and create() can be used to implement shallow copies, and create() can also be used to implement inheritance. However, these two methods still have a lot of tiny holes, so let’s see.
Object.assgin()
If only one obj is passed, return a shallow copy of obj. If more than one argument is passed, pass the first obj its own, enumerable properties for all subsequent objects. And change the first object. Each object property has four different values: Value, Enumerable, 64x and Writable. DefineProperty can be set via Object.defineProperty. Look at the code.
let obj1 = {
1: [1.2.3].a: 'asdfg'.2: 123456
}
let obj2 = {
1: 123.q: '12342'.b: [12.3.4]}let obj3 = {
23: 4
}
Object.defineProperty(obj3, '23', {
value: 12.enumerable: false.configurable: true.writable: true
})
let a = Object.assign(obj1, obj2, obj3)
let b = Object.assign(obj2)
console.log(a);
console.log(b);
console.log(obj1);
console.log(obj2);
console.log(obj3);
Copy the code
Because the properties of obj3 are not enumerable, they will not be added to new objects.
Object.create()
When the argument is an object, the properties on the OBJ prototype chain are inherited.
let obj1 = {
1: 123.2: [1.2.3].a: 'asdf'
}
let obj2 = {
1: 321.q: 123423.b: 'asdfasd'
}
obj1.__proto__ = obj2
let a = Object.create(obj1)
console.log(a);
console.log(a.__proto__);
Copy the code
The newly created A object inherits properties from the obj1 stereotype chain.
If there are two parameters, the second parameter passed in is an attribute. Note that the parameter is an attribute of the object. The enumeration property must be set to true before it can be added to its property by the new object.
let obj1 = {
1: 123.2: [1.2.3].a: 'asdf'
}
let obj2 = {
1: 321.q: 123423.b: 'asdfasd'
}
obj1.__proto__ = obj2
let a = Object.create(obj1, {
own1: {
value: 234
},
own2: {
value: 1234.enumerable: true}})console.log(a);
console.log(a.__proto__);
Copy the code
The first property, own1, is not set to enumeration and defaults to false, so it will not be added.
The second property own2 sets enumeration to true and is added to its own property.
Record the record!