February 23, 2009
Javascript objects: And what is this?
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
- If you are not in an object, this refers to the global window object.
- If you are in an object’s method, this refers to that object,
- 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:
RSS / Atom feed