🔸bound method

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`

Last updated