# 💾 add default properties

{% hint style="info" %}
假設： <mark style="color:blue;">defaults</mark> 是有預設值的物件，<mark style="color:blue;">obj</mark> 是要附加這些預設值的物件。
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
{% hint style="danger" %}
錯誤做法：以下的做法，obj 原來的屬性反而會被預設值覆蓋掉❗️
{% endhint %}

```javascript
Object.assign(obj, defaults)    // ❌ 
```

{% hint style="success" %}
正確做法：
{% endhint %}

```javascript
//                  ╭╮ <-- start with a new object
obj = Object.assign({}, defaults, obj)    // ✅ 
//                                ╰─╯ <-- override defaults with obj
```

也可以用 [Spread syntax (...)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) 來寫：

```javascript
obj = {...defaults, ...obj}
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] (2020) JavaScript: The Definitive Guide (6.7 Extending Objects)
  {% endtab %}

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

* [Spread syntax (...)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
  {% endtab %}
  {% endtabs %}
