Every active execution context owns a this value. It is used for self referring script statements.
The specific this value of an execution context depends on the caller and the type of code being executed. This is determined on entry to an execution context. The this value associated with an execution context is immutable and therefore cannot be changed from a script.
A this value is considered to be a primary expression.
The this keyword is often used inside function bodies that are registered with a prototype. When it is executed, the function can refer to its owning object without having to know what sort of object it is. We can use this to write a function that can be used with several kinds of object.
If the this keyword is used inside an event handler, it refers to the object that the event belongs to. We can exploit this to build event handlers that support many objects and can be called by different event types.
If the this keyword is used outside of all functions (in global code) it refers to the Global object. A this property used in a script will therefore return that global object. In fact it will return an object of type Window.
Other object types will be returned according the context in which the property is applied.
The example shows how the this keyword can be used to enhance the prototype of an object.
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
// See what the scope rules define for 'this'
document.write(this);
document.write("<BR>");
document.write(typeof this);
document.write("<BR>");
// Create a user defined prototype
function AnimalClass()
{
return "Animal";
}
function Animal(aSpecies, aHabitat)
{
this.species = aSpecies;
this.habitat = aHabitat;
this.toString = AnimalClass;
}
// Instantiate an animal
myAnimal = new Animal("Cow", "Field");
document.write("Object: " + myAnimal + "<BR>");
document.write("Species: " + myAnimal.species + "<BR>");
document.write("Habitat: " + myAnimal.habitat + "<BR>");
</SCRIPT>
</BODY>
</HTML>| See also: | Execution context, Method, Primary expression, Reference |
ECMA 262 edition 2 - section - 10.1.6
ECMA 262 edition 2 - section - 10.1.7
ECMA 262 edition 2 - section - 11.1.1
ECMA 262 edition 3 - section - 10.1.6
ECMA 262 edition 3 - section - 10.1.7
ECMA 262 edition 3 - section - 11.1.1
Wrox Instant JavaScript - page - 30
Wrox Instant JavaScript - page - 53
| Prev | Home | Next |
| THEAD.vAlign | Up | Thousands separator |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. | ||