Monday, July 16, 2007

Peter-Paul Koch: The this keyword (in javascript)

Itt van az egesz, de a lenyeg:

What does this refer to in the function doSomething()?

function doSomething() {
this.style.color = '#cc0000';
}

If you want to use this for accessing the HTML element that is handling the event, you must make sure that the this keyword is actually written into the onclick property. Only in that case does it refer to the HTML element the event handler is registered to. So 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

alert(element.onclick)
you get

function onclick()
{
doSomething()
}

Examples - copying

this is written into the onclick method in the following cases:
element.onclick = doSomething
element.addEventListener('click',doSomething,false)
element.onclick = function () {this.style.color = '#cc0000';}

Examples - referring

In the following cases this refers to the window:

element.onclick = function () {doSomething()}
element.attachEvent('onclick',doSomething)