Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

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

I find this pattern all over the ExtJS source code.

method: function() {
  var me = this;
  ...
  me.someOtherMethod();
}

Why don't they just use this? Is there some advantage to always often defining me (outside of not having to type 2 characters)? I can understand if they are trying to maintain the context via closure, but it's done in places where there is no closure at all.

An example from Ext.panel.Panel:

disable: function(silent) {
    var me = this;

    if (me.rendered) {
        me.el.addCls(me.disabledCls);
        me.el.dom.disabled = true;
        me.onDisable();
    }

    me.disabled = true;

    if (silent !== true) {
        me.fireEvent('disable', me);
    }

    return me;
},
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...