Gonna explore where this can go wrong by using a series of scenarios.
Scene 1: Passing a function that uses this as a callback function
Imagine a view with a button. The button has an id of yoke and jQuery is being used.
Soooooo I expected a joke, but got undefined. In this scenario, the invoker is button, so this is set to the jQuery wrapped object. I’m certain this jQuery object does not have subject or joke properties…
One way of fixing the context of this for this scenario is to use the bind() method to hardcode the value of this inside bizarre.makeJoke() like so:
Scene 2: Using this inside a closure
What happened to Momo? Inside the forEach method, an anonymous function was passed as the callback. This anonymous function cannot access its parent function’s this. This issue can be addressed by saving the parent function’s this to a local variable that is still accessible by the anonymous function.