It is worth noting why JS has the
this keyword at all. Normally, we would expect it only in those languages which also have the corresponding
class keyword. That’s what C++, Java and C# have taught us: that
this represents the current object of a class when used inside one of its methods. It only makes sense, then, to use
this keyword in a class scope, denoted by the
this even there?
Greeting is technically a function and is defined as one, but semantically it works more like constructor for the
Greeting “class”. As for
this keyword, it refers to the object being created by such a constructor when invoked by
new statement – another familiar construct, by the way. Additionally,
this also appears inside
greet method and does its expected job, allowing access to the
text member of an object that the method was called upon.
So it would seem that everything with
this keyword is actually fine and rather unsurprising. Have we maybe overlooked something here, looking only at half of the picture?…
Well yes, very much so. And not even a half but more like a quarter, with the remaining three parts being significantly less pretty – to say it mildly.