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.
Learn how and why
this
behaves the way it does, then read the code you're working on.Don't trust some magic functionality, you might always end up with unexpected results if you don't know/read the code.
There's simply no single awesome solution for this "problem".
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.fn
is 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
apply
orcall
function 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
this
is the best way to avoid common mistakes.