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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s