JavaScript - This

Saturday, June 5th, 2010 | Uncategorized

One of the most powerful JavaScript keywords is this.

http://www.quirksmode.org/js/this.html

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.

However, if you use inline event registration

<element onclick=”doSomething()”>

you do not copy the function! Instead, you refer to it, and the difference is crucial.

Examples:

element.onclick = doSomething
element.addEventListener(’click’,doSomething,false)

<element onclick=”doSomething(this)”>

function doSomething(obj) {
obj.style.color = ‘#cc0000′;
}

No comments yet.

Leave a comment

Search