用法1:替换数组的值
let a = [1,2,3],b = [4,5]
console.log( Object.assign(a,b)); // 后面的值覆盖前面的值,[4,5,3]
用法2:为对象添加属性
下面是es5的写法:this.xxx =xxx
// es5的写法
class Test{
constructor(x,y){
this.x =x
this.y = y
}
sum(){
return this.x + this.y
}
}
let t = new Test(1,2)
console.log(t.sum());
用Object.assign的写法
// Object.assign的写法
class Test2{
constructor(x,y){
Object.assign(this,{x,y})
}
sum2(){
return this.x + this.y
}
}
let t2 = new Test2(1,2)
console.log(t2.sum2());
用法3 深度克隆对象
// 用法3 深度克隆对象
let clone = (orignObj) => {
let originProto = Object.getPrototypeOf(orignObj)
return Object.assign(Object.create(originProto), orignObj)
}
let obj3 = { name: 'zs', age: 12 }
console.log(clone(obj3));
用法4:合并对象属性
下面这种写法,合并后,原来的两个对象都已经改变
// example1
let obj = {name:'zs'} ,obj2 = {name:'zs',age:12}
let merge = (target, ...v) => Object.assign(target, ...v)
console.log(merge(obj,obj2));// {name:'zs',age:12}
console.log(obj,obj2); // 合并后,两个对象都已经改变,值都是 {name:'zs',age:12}
如果不想改变原来的对象,可以用下面这个写法
// example2 合并后,返回一个新对象,不更改原有对象的属性
let merge2 = (...v) => Object.assign({}, ...v)
console.log(merge2(obj, obj2));// {name:'zs',age:12}
console.log(obj); // 原来的对象保持原样 {name:'zs'}
console.log(obj2); // 原来的对象保持原样 {name:'zs',age:12}
//合并对象,还可以用展开操作符
let obj5 = {name:'zs'},obj6 = {age:12}
let newOjb = {...obj5,...obj6}
console.log(newOjb);
用法5.为默认对象新增属性
const DEFAULTS = { name: 'zs', age: 13 } // 默认对象
let createObjWithDefault = (opt) => Object.assign({}, DEFAULTS, opt)
console.log(createObjWithDefault({ 'addr': 'gz' }));