Monday, June 6, 2011

Javascript "this" Keyword

In Javascript the "this" always refers the "owner" of the function being executed, or rather, to the object that a function is a method of. Below are a few different examples:

In this first example "this" refers to the global "window" object. If you do not reference a specific object then "this" refers to the global "window" object by default.

function doSomething()
{
  alert(this == window); //the result will be true
}
doSomething();

In this second example "this" refers to the HTML/DOM object that was retrieved using the getElementById method.

var element = document.getElementById('something');
function doSomething()
{
  alert(this == element); //the result will be true
}
element.onclick = doSomething;

In this third example "this" refers to the object that was instantiated using the "new" keyword. This is very similar to the previous example.

var object = new Object();
object.doSomething = function()
{
  alert(this == object); //the result will be true
}
object.doSomething();

Please be aware that you must pass "this" along as a parameter if you reference another function from an HTML event attribute such as onclick.

Click Here
function doSomething(reference)
{
  var element = document.getElementById('something');
  alert(reference == element); //the result will be true
  alert(this == element); //the result will be false
  alert(this == window); //the result will be true 
}

No comments:

Post a Comment