📘this
🚧 under construction
JS ⟩ execution context ⟩ lexical environment ⟩ environment record ⟩ "this"
Within the body of a method, "this" evaluates to the object on which the method was invoked.
property of an execution context.
the object “before dot” (the one who calls the method).
"this" determined on call site❗️ (runtime), not by function declaration (compile-time).
but there are exceptions, 👉 see:arrow function arrow function as class field❗️
this
is not fixed in a method.
is passed (at runtime) by the function call. 👉 method binding.
arrow functions don’t have “own” this, it’s taken from the "outer context" .
the body of a class has a this context.
value of "this" determined on call site❗️
environment record - where the value of "this" is stored.
"this" in event handler - the element which has the handler on it.
a class's body has its this context. ( 👉 arrow function arrow function as class field❗️)
arrow function has no own this:
arrow functions used arrow function as argument
arrow functions used arrow function as method❗️
Once a method is passed somewhere separately from the object – "this" is lost.
const user = {
name: "John",
sayHi() { console.log(`Hi, ${this.name}!`) }
};
// ╭────────╮ <---- passed method
setTimeout(user.sayHi, 1000); // Hello, undefined! 🧨💾 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 = `globalObject` or `undefined` ❗
// ❗this.name = `undefined` or ⛔ TypeError❗
// ❗Hi, I am undefined.
// ❗... (sayHi() called by [object global])問:「如何利用 Object.defineProperty() 定義一個新的屬性,它的值是一個物件、具有物件方法,然後在此方法內參照原物件(要定義新屬性的物件)」❓
Last updated
Was this helpful?