Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

extjs - JavaScript "me" = "this", why?

I saw in many source codes:

var me = this;

specially in Ext-JS 4 (JS framework). Why doing such thing? Is there any other reason or you just want for a variable to be called like "me" instead of "this"?

Thank you.

question from:https://stackoverflow.com/questions/13364503/javascript-me-this-why

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

1 Answer

0 votes
by (71.8m points)

Usually so you can keep a reference to this inside a scope in which this refers to something else (like a callback function, for example).

Consider this example, in which the click event handler function has a different context to what you may expect (this doesn't refer to an instance of MyClass):

var MyClass = function (elem) {
    this.elem = elem;
    this.name = "James";
    elem.addEventListener("click", function () {
        alert(this.name); //oops
    }, false);
};

Now consider this example, in which we store a reference to the value of this inside the constructor function, and use that inside the callback function:

var MyClass = function (elem) {
    var me = this;
    this.elem = elem;
    this.name = "James";
    elem.addEventListener("click", function () {
        alert(me.name); //works!
    }, false);
};

The callback function can refer to a variable that was declared in the outer function, even after that function has returned (the MyClass constructor returns as soon as it's executed the addEventListener). This is a demonstration of a closure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...