# bound method

{% tabs %}
{% tab title="💾 程式" %}
```javascript
const { log } = console;

// --------------------------------------------------------
// ⭐ "regular functions/methods" has a "dynamic" `this`,
//    it depends on the "context" of the call.
// ⭐ "arrow functions" have no own `this`❗️
//    `this` is bound to the "context" (the instance).
// --------------------------------------------------------

class Button {

    // --------------------
    //     class fields
    // --------------------
    // ⭐ class fields are stored in the "instnace" itself❗️
    
    // --------------------------------------------------------------
    // ⭐ arrow function as a "bound method"
    boundClick = () => { log(this.value) }   // 🔗 `this` = instance
    //           ╰── ⭐️ arrow function ──╯
    // --------------------------------------------------------------

    // ⭐ regular function as a "dynamic method"
    click = function(){ log(this.value) }    // ⚠️ `this` is dynamic❗️
    //      ╰─── ⭐️ regular function ───╯

    // ---------------
    //     methods
    // ---------------
    // ⭐ methods are stored in the "prototype"❗️

    // init
    constructor(value) {
        this.value = value;
    }

    // regular method
    dynamicClick() { log(this.value) }        // ⚠️ `this` is dynamic❗️
}

// test code
let button = new Button('hello');

let boundClick = button.boundClick;      // 🔗 `this === button`
boundClick();                            // "hello"

// -----------------------------------------------------------
//  ⛔️ TypeError: Cannot read property 'value' of `undefined`
// -----------------------------------------------------------
let click1 = button.dynamicClick;    // ⚠️ `this` is lost❗️
click1();                            // 🧨 `this === undefined`

let click2 = button.click;           // ⚠️ `this` is lost❗️
click2();                            // 🧨 `this === undefined`
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] JS.info ⟩&#x20;
  * [ ] class ⟩ [Making bound method with class fields](https://javascript.info/class#making-bound-methods-with-class-fields)
  * [ ] [Arrow functions revisited](https://javascript.info/arrow-functions)
{% endtab %}

{% tab title="👥 相關" %}
* made available by [arrow](../../func/arrow "mention") throug [field](field "mention").
{% endtab %}
{% endtabs %}
