You don’t need to remember to bind your functions every time.
Creating a new Foo instance and calling doStuff() on it will get you “baz” logged to the console as expected. So in this case we actually know where this is pointing to and what to expect. We are sure this works:
One way to solve this is by telling the function where this should be pointing to using the Function.prototype.bind method. So, if we replace the last line of the previous snippet with something like this, we get the correct bits logged to the console:
setTimeout(foo.doStuff.bind(foo), 500); // Logs "baz", we're good
We added the bind call at line 5 and now whenever Foo.doStuff is called, we know for sure that this will point to a Foo instance and you don’t have to bind the function every time because it’s already bound in the constructor. Pretty neat, eh?
Since we’re in this subject, I suggest you take look at these links if you haven’t already: