Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If your library is doing this in places where there are no embedded closures/callbacks that might have their own value of <code>this</code>, 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.</p> <p>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:</p> <pre><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; }, </code></pre> <hr> <p>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 <code>this</code>, but those callbacks will have their own value of <code>this</code> so assigning:</p> <pre><code>var me = this; </code></pre> <p>or more commonly in other code I've seen:</p> <pre><code>var self = this; </code></pre> <p>is a way of retaining access to that object even in a callback that has a different value of <code>this</code>.</p> <p>Here's a generic example:</p> <pre><code>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); }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload