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);
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…