Tuesday, September 11, 2007

Javascript keyword "this"

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

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. hen we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

An onclick property, though, is owned by the HTML element it belongs to.

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.

However, if you use inline event registration

<element onclick="doSomething()">

you do not copy the function! Instead, you refer to it, the this keyword once again refers to the global window

No comments: