合并对象
var obj = {a: 1}
var tar = {}
console.log(Object.assign(tar, obj))
console.log(tar === obj)
var obj = {
firstName: 'Yang'
}
var obj2 = {
lastName: 'Lance'
}
var copy = Object.assign(obj, obj2);
console.log(copy === obj)
const tar = {a: 1};
const tar1 = {b: 2, c: 2};
const tar2 = {c: 3};
Object.assign(tar, tar1, tar2);
console.log(tar);
⭐️ 使用包装类
var test = Object.assign(undefined, {a: 1})
var test = Object.assign(null, {a: 1})
var test1 = Object.assign(1, {a: 1})
var test2 = Object.assign(true, {a: 1})
var test3 = Object.assign('aa', {a: 1})
console.log(test1)
console.log(test2)
console.log(test3)
⭐️ 第二个参数,在转换为对象的时候,参数的可枚举性需要为真
var test1 = Object.assign({a: 1}, undefined);
var test2 = Object.assign({a: 1}, 1);
var test3 = Object.assign({a: 1}, '123');
var test4 = Object.assign({a: 1}, true);
console.log(test1);
console.log(test2);
console.log(test3);
console.log(test4);
var test1 = 'abc';
var test2 = true;
var test3 = 10;
console.log(new Object(test1)) // 转为类数组,可以枚举
console.log(new Object(test2))
console.log(new Object(test3))
⭐️ assign 继承属性和不可枚举属性不能够拷贝
var obj = Object.create({foo: 1}, {
bar: {
value: 2
},
baz: {
value: 3,
enumerable: true
}
})
console.log(obj)
console.log(Object.assign({}, obj))