jQuery in Action
330
APPENDIX
JavaScript that you need to know but might not!
in a function call. We can also assign
Function
instances to properties of objects,
and that's where things get really interesting. Read on...
A.2.3 What's this all about?
OO
languages automatically provide a means to reference the current instance of
an object from within a method. In languages like Java and
C++
, a variable
named
this
points to that current instance. In JavaScript, a similar concept exists
and even uses the same
this
keyword, which also provides access to an object
associated with a function. But
OO
programmers beware! The JavaScript imple-
mentation of
this
differs from its
OO
counterparts in subtle but significant ways.
In class-based
OO
languages, the
this
pointer generally references the
instance of the class within which the method has been declared. In JavaScript,
where functions are first-class objects that aren't declared as part of anything, the
object referenced by
where functions are first-class objects that aren't declared as part of anything, the
object referenced by
this
--termed the function context--is determined not by how
the function is declared but by how it's invoked.
This means that the same function can have different contexts depending on
how it's called. That may seem freaky at first, but it can be quite useful.
In the default case, the context (
this
) of an invocation of the function is the
object whose property contains the reference used to invoke the function. Let's
look back to our motorcycle example for a demonstration, amending the object
creation as follows (additions highlighted in bold):
look back to our motorcycle example for a demonstration, amending the object
creation as follows (additions highlighted in bold):
var ride = {
make: 'Yamaha',
model: 'V-Star Silverado 1100',
year: 2005,
purchased: new Date(2005,3,12),
owner: {name: 'Spike Spiegel',occupation: 'bounty hunter'},
whatAmI: function() {
return this.year+' '+this.make+' '+this.model;
}
};
To our original example code, we add a property named
whatAmI
that references a
Function
instance. Our new object hierarchy, with the
Function
instance assigned
to the property named
whatAmI
, is shown in figure A.3.
When the function is invoked through the property reference as in
var bike = ride.whatAmI();
the function context (the
this
reference) is set to the object instance pointed to
by
ride
. As a result, the variable
bike
gets set to the string 2005 Yamaha V-Star