JavaScript "me" = "this", why?

提出了一个问题:JavaScript “me” = “this”, why?,或许与您遇到的问题类似。

回答者James Allardice给出了该问题的处理方式:

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.

希望本文对你有帮助,欢迎支持JavaScript中文网

原文链接:stackoverflow.com

上一篇:custom-guider
下一篇:comparing ECMA6 sets for equality

公众号

欢迎 JavaScript 爱好者