PDA

View Full Version : Why and when to use me instead of this?



drgomesp
14 Jan 2012, 12:31 PM
Why did people start using
var me = this on ExtJS 4?

When should I use
this and
me?

slemmon
14 Jan 2012, 1:04 PM
Quite likely someone can explain this more elegantly that I can, but...
the this keyword changes when you have functions nested inside of functions. So, you can create a 'me' variable to retain a reference to your original 'this' even within nested functions.

Try the following to see how the reference of 'this' is different within the Ext.each function (thus losing reference to the button) and how the reference to the button can be retained by first setting up 'var me = this'.


Ext.create('Ext.Button', {
text: 'Click me',
renderTo: Ext.getBody(),
handler: function() {
var me = this
, arr = [1];
Ext.each(arr, function () {
console.log(this);
console.log(me);
})
}
});

skirtle
14 Jan 2012, 6:30 PM
Scoping benefits are not the only reason. See this article from Ed Spencer (Sencha dev) on how it helps with minification:

http://edspencer.net/2010/06/writing-compressible-javascript.html