❗️Object.assign copies with getter/setter

Object.assign() copies with "get/set" operations, so if:

  • source object has a getter method, or

  • target object has a setter method

⭐ they will be invoked❗ during the assignment, not copied❗.

如果沒正確理解這個「複製過程」,可能會產生下列問題:

⛔️ Object.assign causing TypeError

// the "source" object
const source = {
    
    // ⭐ function copied ✅
    max() {
        console.log(this === source);
        return 3;
    },
    
    // ⭐ getter invoked❗, NOT COPIED❗(during the assign❗)
    get maxRowLength() {
        return this.max();
    },
};

// ⭐ during `Object.assign`:
// ---------------------------------------------
// • target.max = source.max 
//   (function copied ✅)
//
// • target.maxRowLength = source.maxRowLength    // ⭐ console: true
//                        ╰⭐ getter invoked ╯
//   (source getter invoked❗, NOT COPIED❗)
let target = Object.assign({}, source);

target.maxRowLength,             // 3
typeof target.maxRowLength,      // 'number'❗ (NOT a getter method❗)
typeof target.max,               // 'function' (copied ✅)

Last updated