用于对象赋值
可以传入多个对象用于合并,同一个属性key,后传入的对象的value会覆盖前面的。
example
let obj1 = {key1: 1, dupkey: 999};
let obj2 = {key2: 2, dupkey: 888};
let obj = Object.assign(obj1, obj2);
console.log(obj);
//{key1: 1, dupkey: 888, key2: 2}
console.log(obj1);
//{key1: 1, dupkey: 888, key2: 2}
也就是说,assign不仅会返回合并后的多个对象,还会对传入的第一个对象进行覆盖。
所以如果需要不覆盖原有参数,两种写法:
let obj1 = {key1: 1};
let obj2 = {key2: 2};
let obj = Object.assign({}, obj1, obj2);
console.log(obj);
//{key1: 1, key2: 2}
console.log(obj1);
//{key1: 1}
let obj1 = {key1: 1};
let obj2 = {key2: 2};
let obj = {};
Object.assign(obj, obj1, obj2);
console.log(obj);
//{key1: 1, key2: 2}
console.log(obj1);
//{key1: 1}