var newObj = Object.assign(target,source1,source2);
target---------------------------目标对象,即合并后最终呈现的对象
source1、source2--------------要进行合并的源对象
newObj-------------------------该对象方法的返回值,等同于目标对象
该方法会将源对象source1、source2自身的属性进行拷贝,合并到目标对象target上,而不拷贝源对象继承的属性,即 prototype的属性不进行拷贝;
example1:目标对象存在源对象上的属性,则该属性的值会被源对象相对应的属性的属性值覆盖掉;
const target = {
x : 0,
y : 1
};
const source = {
x : 1,
z : 2 ,
fn : {
number : 1
}
};
Object.assign(target, source);
//console.log( target,"target" ); // target {x : 1, y : 1, z : 2, fn : {number : 1}}
//console.log( source,"source" ); // source {x : 1, z : 2, fn : {number : 1}}
此时,目标对象已经浅拷贝成功源对象,二者的共有属性已绑定,修改目标对象时,源对象对应的属
性及其值也会相应的发生变化
target.fn.num = 2;
//console.log( source,"source" ); // source {x : 1, z : 2, fn : {number : 2}}
example2:只能拷贝自身的属性,不能拷贝prototype
function Person(){
this.name = 1
};
Person.prototype.country = 'china';
let student = new Person();
student.age = 29 ;
const young = {insterst : 'sport'};
Object.assign(young,student);
//console.log(young) young {instest : 'sport' , age : 29, name: 1}
example3:数组会当成对象处理,其索引下标值作为属性来进行合并
var newObj = Object.assign([1, 2, 3], [4, 5])
//console.log( newObj ) // [4, 5, 3]