A, Object.assign ()
Object.assign () method is used to enumerate all the attribute values are copied from one or more source object to the target object. It will return to the target object. And source object will be modified.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
If the target object property with the same key, the attributes are covered by the source object property. Properties of the source object will similarly cover behind the front of the properties of the source object. Supports a plurality of objects are merged, if you do not modify the target object, the target object may be changed} {empty,
例如:const returnedTarget = Object.assign( {} , source,source);
Object.assign
The method will only copy source and the object itself may be enumerated attributes to the target object. The method uses the source object [[Get]]
and the target object [[Set]]
, it will call the relevant getter and setter. Accordingly, it is assigned attributes, rather than just copying or define new attributes. If the merge source contains getter, which may make it unsuitable for the new property incorporated into the prototype. In order to define the attribute (which may include enumeration of) to the prototype should be used Object.getOwnPropertyDescriptor()
and Object.defineProperty()
.
String
Type and Symbol
type attribute will be copied.
In the case of an error, for example, if the property is not writable, cause TypeError
, if you add any properties before throwing error, you can change the target
subject.
Note, Object.assign
not in those source
target value null
or undefined
throw the wrong time.
Second, the use of loop through
This little trouble on the
var obj1={name:'张三'};
var obj2={age:18};
for(var key in obj2){
if(obj2.hasOwnProperty(key)===true){
obj1[key]=obj2[key];
}
}
console.log(obj1);