If you're used to some other programming languages like C++, Java, or C#, the first thing about understanding this
in JavaScript is: It's completely different from this
in those other languages, even though it looks very similar and sometimes even acts similarly.
When you're creating the t
object, you capture the value of this
as of when the object is created and store it in the property g
. So g
will be whatever this
was when t
was created. Because this
refers to the global object (window
, on browsers) by default unless you're using strict mode, that's what t.g
will be.
In contrast, your t.f
function is getting called and is returning the value of this
that exists within the call. In JavaScript (for now), this
is determined entirely by how a function is called rather than where it's defined. In particular, when you call a function as part of an expression that retrieved the function from a property reference, this
is set to the object within the call. This is a complex way of saying when you do t.f()
, during the call to f
, this
will be t
.
Some further reading (on my blog):