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() { = '#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 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.


Leave a Reply

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

You are commenting using your 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 )


Connecting to %s