In JavascriptthisAlways refers to the "owner" of the function we're re executing, or
Rather, to the object that a function is a method.
function doSomething() { this.style.color = '#cc0000';}
------------ window --------------------------------------| / \ || | || this || ---------------- | || | HTML element | <-- this ----------------- || ---------------- | | doSomething() | || | | ----------------- || -------------------- || | onclick property | || -------------------- || |----------------------------------------------------------
1. Copy---------------Traditional event registration--------------the element
element.onclick = doSomething;
The function is copied in its entirety toonclickProperty (which now becomes a method). So if the event handler is executedthisRefers
To the HTML Element and ItscolorIs changed.
------------ window --------------------------------------| || || || ---------------- || | HTML element | <-- this ----------------- || ---------------- | | doSomething() | || | | ----------------- || ----------------------- | || |copy of doSomething()| <-- copy function || ----------------------- || |----------------------------------------------------------
Examples of elements:
element.onclick = doSomethingelement.addEventListener('click',doSomething,false)element.onclick = function () {this.style.color = '#cc0000';}<element onclick="this.style.color = '#cc0000';">
2. Reference ------------- inline
Event registration ------------ this points to the global variable window
doSomething();
So it says "Go to dosomething () and execute it." When we arrivedoSomething()ThethisKeyword once again refers
To the global window object and the function returns error messages.
This indicates an example of a window object.
element.onclick = function () {doSomething()}element.attachEvent('onclick',doSomething)<element onclick="doSomething()">
From: http://www.quirksmode.org/js/this.html