"this" determined on call site❗️

(usually) "this" is determined on run-time

JSobject ⟩ "this" ⟩ determined on call site

(usually) the value of this is:

but there are exceptions, 👉 see:arrow function arrow function as class field❗️

💾 replit:this determined on call site

// object
let user = {

    name: "Joe",

    sayHi() {
        
        console.log(`Hi, I am ${this.name}.`);
        //                      ╰──╯  
        //                        ↳ ⭐️ value of `this` is NOT determined here.
        
        console.log(`... (sayHi() called by ${this})`)
    }
};

// ❗assign a new name
let f = user.sayHi;    // ⭐️ the function is NOT invoked here❗

// ⭐️ call site #1
user.sayHi();          // ⭐️ this === user (object before "dot")

// Hi, I am Joe.
// ... (sayHi() called by [object Object])

// ⭐️ call site #2
f();                   // ❗this      = window / globalObject / undefined❗
                       // ❗this.name = undefined / undefined / ⛔ TypeError❗

// ❗Hi, I am undefined.
// ❗... (sayHi() called by [object global])

Last updated