The 'this' Keyword
How 'this' is determined at call time
"use strict";
const user = {
name: "Alice",
greet() {
return `Hi, I'm ${this.name}`;
},
};
// Method call — this = user
console.log(user.greet());
// Detached — this = undefined (strict)
const greet = user.greet;
try {
console.log(greet());
} catch (e) {
console.log("detached:", e.message);
}
// Rebind with bind
const bound = user.greet.bind(user);
console.log(bound());
// Arrow functions capture lexically
const other = {
name: "Bob",
delayedGreet() {
setTimeout(() => {
console.log(`lexical this: ${this.name}`);
}, 0);
},
};
other.delayedGreet();
// call and apply
function introduce(prefix, suffix) {
return `${prefix} ${this.name}${suffix}`;
}
console.log(introduce.call(user, "Hello,", "!"));
console.log(introduce.apply(user, ["Hola,", "."]));