# override class fields

[JS](../../..) ⟩ [types](../../type) ⟩ [class](..) ⟩ [inheritance]() ⟩ override class fields

{% tabs %}
{% tab title="⭐️ 重點" %}
⭐️ <mark style="color:orange;">**class fields**</mark> initialization：

{% hint style="warning" %}
The <mark style="color:purple;">**class fields**</mark> are initialized:

* <mark style="color:red;">**base class**</mark>: **before** <mark style="color:purple;">**`constructor()`**</mark>
* <mark style="color:orange;">**derived class**</mark>: immediately **after** [<mark style="color:purple;">**`super`**</mark>](super)<mark style="color:purple;">**`()`**</mark>&#x20;
{% endhint %}

👉 參閱： [derived-class-init](derived-class-init "mention") 看完整的「初始化」過程。
{% endtab %}

{% tab title="💾 程式" %}
💈範例：[replit](https://replit.com/@pegasusroe/JS-override-class-fields#index.js)



<img src="https://2527454625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MfvEFZnSBhKT6fJmus0%2Fuploads%2FqqRD2ltCjQ9vzd5GOWqN%2Ffile.drawing.svg?alt=media&#x26;token=f76c240d-9d70-403a-8926-0f4f4b43310b" alt="overridden class fields not fully initialized" class="gitbook-drawing">

```javascript
// base class
class A {
    name = 'A';
    constructor() { log(this.name); }
}

// derived class
class B extends A {

    name = 'B';            // 🔸 overridden class fields

    constructor(){
        // ❗ `this` doesn't exist before `super()`
        super();
        log(this.name);
    }
}

new A();        // "A"
new B();        // "A"❗, "B" 
```
{% endtab %}

{% tab title="❗狀況" %}


<img src="https://2527454625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MfvEFZnSBhKT6fJmus0%2Fuploads%2FEgPzTsuc3KccSXKPpzk9%2Ffile.drawing.svg?alt=media&#x26;token=cfae9d02-95db-4616-8b8d-91879de40eae" alt="overridden class fields not fully initialized" class="gitbook-drawing">

```javascript
class A {
    name = 'A';
    constructor() { 
        // ⭐️ overridden class fields not fully initailized at this point
        log(this.name); 
    }
}

class B extends A {
    name = 'B';        // ⭐️ overridden class field
}

new A();     // "A"
new B();     // "A"❗
```
{% endtab %}

{% tab title="📗 參考" %}
* [x] JS.info ⟩ [override class fields: a tricky note](https://javascript.info/class-inheritance#overriding-class-fields-a-tricky-note) ⭐️
{% endtab %}

{% tab title="👥 相關" %}
* see how [field](../member/field "mention") are initialized in [derived-class-init](derived-class-init "mention").
* <mark style="color:orange;">**derived class fields**</mark> are initialized <mark style="color:yellow;">**immediately**</mark> after [<mark style="color:purple;">**super()**</mark>](super).
{% endtab %}
{% endtabs %}
