What is the value of var me = this; What is the value of var me = this; javascript javascript

What is the value of var me = this;


If your library is doing this in places where there are no embedded closures/callbacks that might have their own value of this, then this is just a "practice" or "style" or "convention" that they decided to follow in their methods. There is NO programming reason to always do it.

In the specific coding example you have now added to your question, there is no reason I'm aware of other than a common coding style. This code would generate the same result in slightly smaller code:

disable: function(silent) {    if (this.rendered) {        this.el.addCls(this.disabledCls);        this.el.dom.disabled = true;        this.onDisable();    }    this.disabled = true;    if (silent !== true) {        this.fireEvent('disable', this);    }    return this;},

When there is a callback or closure involved, this is often done because there are callbacks used inside the method where they still want a reference to this, but those callbacks will have their own value of this so assigning:

var me = this;

or more commonly in other code I've seen:

var self = this;

is a way of retaining access to that object even in a callback that has a different value of this.

Here's a generic example:

document.getElementById("myButton").onclick = function () {    var self = this;       // save reference to button object use later    setTimeout(function() {        // "this" is not set to the button inside this callback function (it's set to window)        // but, we can access "self" here         self.style.display = "none";    // make button disappear 2 seconds after it was clicked    }, 2000);};


One reason is because with minification, me can become much shorter than this.


Besides the style reasons and the minification reasons, I decided to look at performance to see if this or self was any faster. I created this jsperf test.

As best I can tell, there is basically no difference in performance in any of the modern browsers that I tried or even IE6 bewtween using this vs. using a local variable like self or me. Chrome is ever so slightly faster with self and the others are too close to call. I think we can rule out any performance reasons. Here's a screen shot of the results I saw:

enter image description here