Because you're kind of abusing the global namespace here, which is bad. this
is usually assigned to window
when there's no other scope. But if that function was handling, say a DOM event, then this
would be the element that fired the event. So long story short, you should usually not rely on this
to be set to something.
Either set it explicitly using call or apply, as very nicely explained here: What is the difference between call and apply?.
Or save a particular this and define your function as a closure around it:
self = window;
self.name = 'Jane Doe';
self.greet = function () {
return 'My name is ' + self.name;
};
console.log(self.greet());
That code makes me feel dirty though. Only clobber the global namespace like that if you Absolutely must. Like, for example, when you're defining the jQuery variable, or the ko variable (with knockout). And even then, don't do it like this :)
Of course this
is totally fine to use, but you should really understand it properly before using it. And that goes beyond the scope of this question.