Java Reference
In-Depth Information
Every function object has a
prototype
property, but it is only useful for constructor functions.
You can think of the
Person.prototype
property as an actual prototype for
Person
objects. Any
properties and methods you assign to
Person.prototype
are usable on all
Person
objects. In fact,
they're more than usable—they're shared!
The functions assigned to
Person.prototype.getFullName
and
Person.prototype.greet
are shared between all objects, or instances, of
Person
. This means that the function object of
one
Person
object's
getFullName
is the exact same function object on another
Person
object's
getFullName
. To express that in code:
var areSame = person1.getFullName == person2.getFullName; // true
But why were
firstName
and
lastName
assigned in the constructor instead of
Person.prototype
?
The
firstName
and
lastName
properties are called
instance data
. Instance data is unique to each
individual object, or instance. So because
firstName
and
lastName
are instance data, we define
them in the constructor—they shouldn't be shared between all
Person
objects.
Creating and using reference type instances
You create instances of your reference type in the same way you created instances of JavaScript's
built‐in types: using the
new
keyword. So to create a new instance of
Person
, you'd write this:
var johnDoe = new Person("John", "Doe");
var janeDoe = new Person("Jane", "Doe");
Here, as with a
Date
object, you have created two new objects and stored them in variables,
johnDoe
and
janeDoe
, but this time it's a new object based on the
Person
type.
Note
The use of the
new
keyword is very important when creating an object
with a constructor. The browser does not throw an error if you do not use the
new
keyword, but your script will not work correctly. Instead of creating a new
object, you actually add properties to the global
window
object. The problems
caused by not using the
new
keyword can be hard to diagnose, so make sure
you specify the
new
keyword when creating objects with a constructor.
You use these objects just like you did in
ch5 _ example8.html
. In the following code, Jane Doe
greets John Doe:
janeDoe.greet(johnDoe);
Even though
getFullName()
and
greet()
are defined on
Person.prototype
, you still call them like
normal methods. JavaScript is intelligent enough to look at
Person.prototype
for those methods.
Now for the million dollar question: Why define a reference type instead of creating plain, but
custom, objects? It's a valid question. Both the objects created in
ch5 _ example8.html
and from the
Person
constructor serve the same purpose: to represent an individual person. The main difference