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