Object.assign usage

1. What is
the Object.assign() method used to assign the values ​​of all enumerable properties from one or more source objects to a target object. It will return the target object.

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. Grammar

Object.assign(target, ...sources)
  • target: target object
  • sources: source object, one or more

3. Precautions

  • Object.assign is just a shallow copy. If there is a reference type in the source object, the memory space pointed to by the pointer of the target object and the pointer of the source object is the same space. If one of them is changed, the other will also change accordingly. The basic type unchanged
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'}}
  • If the property in the target object has the same key, the property will be overwritten by the property in the source object. Properties of later source objects will similarly override properties of earlier source objects.
const a ={
    
     name: '张三'}
const b ={
    
    name: '李四'}
const c = {
    
    name: '王五'} 
Object.assign(a,b,c) 
console.log(a) 
// {name: '王五'}
  • properties of string type, null, undefined and Symbol types will be copied
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}
  • Only the enumerable properties of the source object itself will be copied to the target object. For non-enumerable properties, they will be automatically ignored when using 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'}
  • For read-only properties, an exception will be thrown when a new object is assigned to overwrite it
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>'

Guess you like

Origin blog.csdn.net/Smile_666666/article/details/123522244