Javascript – The ‘this’ keyword

In JavaScript this refers to the “owner” of the function we’re executing or to the object that a function is a method of. When we define our function doSomething() in 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.

function doSomething() {
this.style.backgroundcolor = '#ff0000';
}

This “ownership” is the result of JavaScript’s object oriented approach. See the Objects as associative arrays page for some more information.

If we execute doSomething() without any more preparation the thiskeyword refers to the window and the function tries to change the style.backgroundcolor of the window. Since the window doesn’t have a styleobject the function fails and produces JavaScript errors.