Many answers, all with useful and correct information, but none of them explains the correct behavior.
In the first example, it only registers Hello foo both times because you create a self variable that references the this object. This self variable is then closed in your greeting function . Therefore, you can call this function self.name you want, it will always have access to self.name , not this.name , so it will always be the same.
You do not do this in your prototype example. There you directly access this.name , and then it really matters how to call the function (see @lwburk's answer).
So, even if you call the first example, for example
foo.greeting.call( window );
it will still access the private variable self and log Hello foo .
jAndy source share