In JavaScript, a function’s this keyword is always bound to an object, what
object that is depends on how the current function was called, so it could be
different each time the function is called.
In this example, as we and anyone else would expect after reading this code,
this refers to MyObject,
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
The next example is a little weird. As you can see my_method is now being called within the context of the global object.
In the previous case my console.log(this) was equivalent to
console.log(MyObject) and here it is equivalent to console.log(global).
1 2 3 4 5 6 7 8 9 10 11 12 | |
But the really interesting stuff happens when using something like jQuery’s
Events with bind/trigger. I’ve seen this be a fairly common gotcha. You
expect this to refer to your object, but it’s actually the object you
triggered your event on,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
Thankfully, this is fixable! All we have to do in bind our object’s methods to that object, to be run in the context of our object whenever they are invoked.
Underscore.js provides this functionality with its bind/bindAll functions, check out
the docs and annotated
sources for more detail.
So we add this after defining our object,
1
| |
And this behaves as we expect! Everybody was Kung fu fighting! Ha!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
