In some cases, the this keyword may not refer to the object I expect it to. (recent example: in an key event, in my XBL)
What’s the best approach to avoid this kind of mistake?
For now, I’m using always the $.fn from jQuery to store my variables, but I’m not sure if it’s the best approach.
Don’t avoid using this. Just use it the right way. Javascript is a prototype based object oriented language. If you create your objects using the object prototype should always know what this refers to.
jQuery.fn is the same thing as
jQuery.prototype.jQuery.fnis just an alias. You can also check the this keyword using instanceof.Another common practice is to call a method and bind the context at that time using the
applyorcallfunction methods. This will guarantee the function’s this context.Here is a simple example.
The first argument of the call method binds the this context and runs the function.
Knowing how to control and check
thisis the best way to avoid common mistakes.