对象的扩展-Object.assign()

1.只会拷贝本身的属性,不会拷贝prototype上的属性

2.如果有同名的属性,后面的会覆盖前面的

3.target如果不是对象,是string,number或者boolean,会先转化为包装类

4.如果target是undefined,null,无法转化为包装类,那么报错

5.如果source不是对象,只有是string,可以计算,否则没有影响

let target = {a: 1};
let source1 = {
    abc: 25,
    cde: 27
};

let source2 = {
    abc: 27,
    x: 17,
    y: 'abc'
};

source1.__proto__.b = 5;
console.log(source1.b);

console.log(Object.assign(target, source1, source2));
console.log(target);
console.log(Object.assign(2, source1, source2));
console.log(Object.assign({}, 'abc', 123, true));
 
=================运行的结果===================

6.Object.assign的拷贝是浅拷贝,不是深拷贝

let target = {
    a: 1,
    b: {
        x: 5,
        y: 7
    }
};

let source = {
    b: {
        z: 9,
        h: 51
    }
}

console.log(Object.assign(target, source));
=================运行的结果===================
 
posted @ 2021-01-24 14:59  #Friday  阅读(101)  评论(0)    收藏  举报