Here’s what he wrote:
I’m trying to get rid of the last global variable, but I can’t get it working. What I’m trying to do is use setTimeout to cause a new sound to be played 3 seconds later. It works just fine if the method and associated data is global (as was the case in your examples for setTimeout. But I’ve encapsulated all my data and functions in objects so my call to setTimeout might look like setTimeout(model.playsound, 3000). The playsound function refers to the sound by “this.mySound” which works perfectly under normal circumstances.
However, when the function gets called from setTimeout, there’s an error because mySound is not defined. I’m guessing it’s because “this” refers to something else when it’s called from the setTimeout function.
this, but there are actually a few situations where it can be tricky to understand why
this is set to what it is. In some situations, you can be quite surprised that
this isn’t set to what you think it should be! One of those tricky situations is when you are assigning or passing a reference to a function that refers to
this (e.g. if the function is actually a method in an object, like in the reader’s situation above).
this in a situation like this, Head First brain-friendly style.
I also prepared a video on this topic earlier this year that’s a good starting point, but doesn’t touch on this specific situation. Once you’ve watched the video, download the Extra (PDF, 3.8Mb), for more details.
I look forward to hearing your feedback, and any remaining questions you might have about how to keep track of
this in your code. We love getting reader questions, so keep sending them in!