Javascript: The this keyword
One of the most powerful JavaScript keywords is this. Unfortunately it is hard to use if you don't exactly know how it works.
Below I explain how to use it in event handling.
Owner
The question that we'll discuss for the remainder of the page is: What does this refer to in the function doSomething()?
function doSomething() {
this.style.color = '#cc0000';
}
In JavaScript this always refers to the "owner" of the function we are executing, or rather, to the object that a function is a method of. When 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.
This "ownership" is the result of JavaScript's object oriented approach.
------------ window -------------------------------------- | / \ | | | | | this | | ---------------- | | | | HTML element | <-- this ----------------- | | ---------------- | | doSomething() | | | | | ----------------- | | -------------------- | | | onclick property | | | -------------------- | | | ----------------------------------------------------------
If we execute doSomething() without any more preparation the this keyword refers to the window and the function tries to change the style.color of the window. Since the window doesn't have a style object the function fails miserably and produces JavaScript errors.
