What does 'this' refer to in the function doSomething()?:
function doSomething() {
this.style.color = '#cc0000';
}
In javascript, 'this' always referer to the owner of the function (the object that a function is a method of). When we define a function in a page, its owner is the page (the window object). An onclick property is owned by the html element it belong to.
So if we want to use 'this' to its full extent we have to take care that the function is owned by the correct HTML element In other words, we have to copy the function to our onclick property:
element.onclick = doSomething;
The function is copied in its entirety to the onclick property (which now becomes a method). So if the event handler is executed, 'this' refers to the HTML element and its color is changed.
We can copy the function to several event handlers. Each time 'this' will refer to the correct HTML element (that owns the copy of doSomething).
However, if you use inline event registration:
<element onclick="doSomething()">
you do not copy the function! Instead, the browser creates a wrapper function which call doSomething(), and the difference is crucial. When we arrive at doSomething() the 'this' keyword once again refers to the global window object and the function returns error messages.
If you do:
element.onclick = doSomething;
alert(element.onclick)
you get
function doSomething()
{
this.style.color = '#cc0000';
}
As you can see the 'this' keyword is present in the onclick method, therefore it refers to the HTML element. But if you do
<element onclick="doSomething()">
alert(element.onclick)
you get
function onclick()
{
doSomething()
}
This is creating a wrapper function which call doSomething(). The 'this' keyword is not present in the onclick method so it doesn't refer to the HTML element.
With inline registration, you can have
<element onclick="any arbitrary javascript code">
and the browser take "any arbitrary javascript code" and wrap a function around it.
**Examples of copying ('this' is present in the onclick method): **
element.onclick = doSomething;
element.addEventListener('click',doSomething,false);
element.onclick = function () { this.style.color = '#cc0000'; }
<element onclick="this.style.color='#cc0000'">
**Examples of creating a wrapper function ('this' refer to window object): **
element.onclick = function () { doSomething() }
element.attachEvent('onclick',doSomething)
<element onclick="doSomething()">
Note the presence of attachEvent(). The main drawback of Microsoft event registration model is that attachEvent() creates a wrapper function and does not copy it. Therefore it is sometimes impossible to know which HTML element currently handles the event.
Combination
When using inline event registration you can also send 'this' to the function:
<element onclick="doSomething(this)">
function doSomething(obj) {
obj.style.color = '#cc0000';
}





