February 23, 2009

Javascript objects: And what is this?

Posted in Software at 03:06 by graham

When writing object-oriented Javascript, there are two occasions when you need to be careful that this is set correctly: In inner functions and in callbacks.

this in inner functions

  1. If you are not in an object, this refers to the global window object.
  2. If you are in an object’s method, this refers to that object,
  3. except in an inner function, when this refers to the global window object again.

Number 3 is what you need to watch for. It is considered a bug in Javascript. Here is an illustration of the three cases:

Read the rest of this entry »