# ❗️Object.assign copies with getter/setter

{% hint style="danger" %}
⭐ [`Object.assign()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) copies with "[get/set](https://lochiwei.gitbook.io/web/js/val/class/member/getter-setter)" operations, so if:

* <mark style="color:yellow;">**source**</mark> object has a <mark style="color:yellow;">**getter**</mark> method, or
* <mark style="color:orange;">**target**</mark> object has a <mark style="color:orange;">**setter**</mark> method

⭐ they will <mark style="color:red;">**be invoked**</mark>❗ during the assignment, <mark style="color:red;">**not copied**</mark>❗.
{% endhint %}

{% hint style="warning" %}
如果沒正確理解這個「複製過程」，可能會產生下列問題：

「 [object.assign-causing-typeerror](https://lochiwei.gitbook.io/web/js/val/obj/extend/object.assign/object.assign-causing-typeerror "mention") 」
{% endhint %}

{% tabs %}
{% tab title="💈範例" %}

* [replit](https://replit.com/@pegasusroe/Objectassign-copies-with-getterssetters#index.js)

```javascript
// 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 ✅)
```

{% endtab %}

{% tab title="📘 手冊" %}

* [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  {% endtab %}

{% tab title="🗣 討論" %}

* [Object.assign() causes TypeError: this.map is not a function](https://stackoverflow.com/questions/72625697/object-assign-causes-typeerror-this-map-is-not-a-function) (我問的)
  {% endtab %}

{% tab title="👥 相關" %}

* [.assigndescriptors](https://lochiwei.gitbook.io/web/js/val/obj/extend/mixin/.assigndescriptors "mention")
* [object.assign-causing-typeerror](https://lochiwei.gitbook.io/web/js/val/obj/extend/object.assign/object.assign-causing-typeerror "mention")
* [app.range.prototype](https://lochiwei.gitbook.io/web/appendix/gas/app/prototypes/app.range.prototype "mention") 也有這個問題 ❓
  {% endtab %}
  {% endtabs %}
