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.

js_this_function

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

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.