js Object.assign 方法
浅拷贝
- Object.assign(target,...,source)
- Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
- 只是将属性值覆盖前面的,如果是引用类型,拷贝引用地址
var a = {a:1,b:3}
var b = {a:10,d:30}
var c = Object.assign(a,b)
console.log(a)// {a:10,b:3,d:30}
console.log(c)// {a:10,b:3,d:30}
var a = {a:1,b:3}
var b = {a:10,d:30}
var c = {f:2}
var d = Object.assign(a,b,c)
console.log(a)// {a:10,b:3,d:30,f:2}
console.log(d)// {a:10,b:3,d:30,f:2}
// 引用类型
var a = {a:1,b:3}
var b = {a:10,c:a}
var c = {a:120,d:120}
var d = Object.assign(b,c)
console.log(b)// {a:120,c:{a:1,b:3},d:120}
console.log(d)// {a:120,c:{a:1,b:3},d:120}
d.a = 0
console.log(b)// {a:0,c:{a:1,b:3},d:120}
console.log(d)// {a:0,c:{a:1,b:3},d:120}
// 更改引用类型值
d.c.a = 0
console.log(b)// {a:0,c:{a:0,b:3},d:120}
console.log(d)// {a:0,c:{a:0,b:3},d:120}
console.log(a)// {a:0,b:3}