Now, I just put
var that = this;
at the top of very method and use 'that' everywhere in the function.Now, I just put
var that = this;
at the top of very method and use 'that' everywhere in the function. initComponent: function() {
var me = this;
me.callParent();
...
Thanks for explaining the rationale; I'd never paid enough attention to understand why they were doing that.Another way is jQuery.proxy(), though that works best for calling a method with the correct context.
Or the numerous ``bind`` functions and methods (which do the same thing).
In fact, ES5's Function prototype even grew a ``bind`` method[0], which is used to partially apply a function (both to bind it to a ``this`` and to bind it to an arbitrary number of arguments).
Some libraries (e.g. underscore) also have a shortcut to bind all methods of an object (or only a subset of those)[1], handy when using methods as event or deferred callbacks
[0] https://developer.mozilla.org/en/JavaScript/Reference/Global...
Something I also find helpful is reminding myself that I'm not just writing a function, but a method for the current object (referenced by 'this').
I agree that in the case where you're creating a closure, you need to create a reference to the scope referenced by 'this' in order to 'enclose' it, however, that doesn't make it a best practice, all the time, as many responses are suggesting.
var _this = this; //vanilla
var $this = $(this); //jQuery
Though, I have encountered people who are really against the $var for stylistic reasons - so ymmv.