this in a Method and in a Function
In short: this is decided by how a function is called, never by
where it was written. Call a function as obj.method() — with an object
right before the dot — and this is obj. Call the exact same function on
its own, with nothing in front, and this is undefined in strict mode
(or the global object in sloppy mode) — even if that call happens to sit
physically inside a method. Being nested inside a method changes nothing;
only the call itself matters.

Call a method, then call it detached
The exact same function, called two different ways, gets two different
this values:
song.play() prints "Blue Hour" — called with song. right before it,
this is song. The very same function, pulled out and stored in fn,
then called as fn() — no object before the dot — throws
TypeError: Cannot read properties of undefined (reading 'title'), because
this is undefined in strict mode, and undefined has no title.
Lose this inside a nested function
Nesting a plain function inside a method does not give that inner
function the method's this — it's still just a plain, detached call when
it runs:
The first log prints "Blue Hour" — play was called as song.play().
The second throws the same TypeError as before — inner() is called on
its own, with nothing in front of the dot, so it gets its own this
(undefined), completely unrelated to play's. Being written inside
play's braces doesn't inherit anything; only the call site decides.
The trap: assuming this means "the object this code lives in"
It's tempting to read this as "the object this function belongs to" —
but functions don't belong to objects the way methods on a class do in
other languages. A function is just a value; assigning it to
song.play doesn't permanently attach song to it. this is re-decided,
from scratch, at every single call.
Quick practice
What does song.play() set this to inside play?
const fn = song.play; fn(); — what is this inside fn now (strict mode)?
A plain function is called from inside a method's body, with no object in front of it. What decides its this?
What best describes how this is determined in a regular function?
Why does console.log(this.title) throw inside a detached, strict-mode function call?
🎯 Your turn
Explain what this is on each console.log line:
const song = { title: "Blue Hour", play() { console.log(this.title); function inner() { console.log(this.title); } inner(); } }; song.play();
(assume strict mode). Why does the second line differ from the first, even
though inner() is written inside play()?
Write your explanation and submit it — there's no code to run here, just your reasoning.
