Object.assign用法

1、是什么
Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。

const a ={
    
     name: '张三'}
const b ={
    
    
   age: '18',
   sex: '女'
}
const c = Object.assign(a,b) 
console.log(c) // {name: '张三', age: '18', sex: '女'}
console.log(a) // {name: '张三', age: '18', sex: '女'}
console.log(a === c) // true

2、语法

Object.assign(target, ...sources)
  • target:目标对象
  • sources:源对象,一个或多个

3、注意点

  • Object.assign只是浅层的拷贝,如果源对象里有引用型,则目标对象的指针和源对象的指针指向的内存空间是同一块空间,改变其中一方,则另一方也会跟着改变,基本类型则不变
let b = {
    
    
  age: '18',
  work:{
    
    
     address: '广州',
     time:'7.30am'
  }
}
let c = Object.assign({
    
    }, b);
console.log(c); // { age: '18', work: {address: '广州', time: '7.30am'}}
c.work.address = '北京'
c.age = '22'
console.log(c); // { age: '22', work: {address: '北京', time: '7.30am'}}
console.log(b); // {
    
    {age: '18', work: {address: '北京', time: '7.30am'}}
  • 如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖。后面的源对象的属性将类似地覆盖前面的源对象的属性。
const a ={
    
     name: '张三'}
const b ={
    
    name: '李四'}
const c = {
    
    name: '王五'} 
Object.assign(a,b,c) 
console.log(a) 
// {name: '王五'}
  • string类型,null,undefined和 Symbol 类型的属性都会被拷贝
const a ={
    
     name: '张三'}
let b = {
    
    
    a1: Symbol("SymbolValue"),
    a2: null,
    a3: undefined
}
let c = Object.assign(a, b);
console.log(c); 
//{name: '张三', a1: Symbol(SymbolValue), a2: null, a3: undefined}
  • 只会拷贝源对象自身的并且可枚举的属性到目标对象,对于不可枚举的属性,使用Object.assign的时候将被自动忽略
let userInfo = {
    
    }
 Object.defineProperty(userInfo, "work", {
    
    
    adrress: '广州',
   // enumerable: false // Object.defineProperty默认就是不可枚举的属性fase
});
Object.defineProperty(userInfo, "time", {
    
    
    value: '11.am',
    enumerable: true
});
let c = Object.assign({
    
    }, userInfo);
console.log(c); 
// {time: '11.am'}
  • 对于只读的属性,当分配新的对象覆盖他的时候,将抛出异常
let userInfo = {
    
    }
Object.defineProperty(userInfo, "time", {
    
    
    value: '11.am',
    writable: false
});
let c = Object.assign(userInfo , {
    
    time: '18.pm'});
console.log(c);
// VM586:6 Uncaught TypeError: Cannot assign to read only property 'time' of object '#<Object>'

猜你喜欢

转载自blog.csdn.net/Smile_666666/article/details/123522244