#77: Pulling a method off its object
Topic: this · Difficulty: ★★
const obj = {
name: 'Ann',
greet() { return 'Hi ' + this.name; },
};
const fn = obj.greet;
console.log(obj.greet());
console.log(fn());Output
Hi Ann Hi undefined
Why
this is not a property of the function itself — it is determined entirely by how a function is CALLED. obj.greet() calls greet as a property access on obj, so this is obj and this.name is 'Ann'. Assigning fn = obj.greet copies only the function value, with no memory of which object it came from. Calling fn() invokes it as a bare function call, and in non-strict mode (which node -e uses) a bare call sets this to the global object rather than undefined — the global object has no name property, so this.name silently evaluates to undefined instead of throwing.