The value of JavaScript’s this keyword can seem puzzling. This post aims to make it a little clearer.
Variables and properties in JavaScript are equivalent:
They are both assigned the same way, they are used the same way in JavaScript expressions, and so on. Is there really any fundamental difference between the variable
iand the propertyiof an objecto? The answer is no. Variables in JavaScript are fundamentally the same as object properties.JavaScript, The Definitive Guide, 4.6, by David Flanagan (NB: See comment below)
It continues that global JavaScript variables - top-level code, so not part of a function - are just properties of the global object. The global object is created automatically when the JavaScript interpreter fires up. If you’re coding for the browser, the Window object is the global object.
The special keyword this crops up in methods, and its value varies depending on how it is invoked. This is perhaps best understood when illustrated.
Illustrate this
1. this object we’re in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
2. this has no fixed abode:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
So, this refers to the object that called the method.
3. Nested objects can obfuscate which object this is, but we can handle it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
4. this works just the same in a constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
The special keyword new creates a new object and calls on the constructor in the context of the new object. As expected, the value of this is the new object.
5. this works just the same when handling events: Click me
1 2 3 4 5 6 7 8 9 | |
JavaScript can respond to events happening in the browser. In the above example, we use document.getElementById to return a link element (an object with its own collection of properties). This has the built-in property onclick. When someone clicks on the link, link.onclick calls the event handler (an anonymous function).
In other words, our event handler operates on the object through which it was invoked: our link element.
6. You can override the default this, e.g.:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
The value of this becomes the object passed to the call method.
Conclusion
Rebecca Murphey probably sums it up best:
In JavaScript, as in most object-oriented programming languages,
thisis a special keyword that is used within methods to refer to the object on which a method is being invoked.
Are you feeling confident about this yet?
Updated 15 Sept. 2012: In strict mode,
thisinside a global function is undefined. Here’s why…
