Java Reference
In-Depth Information
A constructor is a function that is called every time one of your objects based on this reference type
is created. It's useful when you want to initialize properties or the object in some way. You need to
create a constructor even if you don't pass any parameters to it or if it contains no code. (In that
case it'd just be an empty definition.) As with all functions, a constructor can have zero or more
parameters.
You've created objects to represent individual people. Next you create a simple reference, called
Person
, to do the same thing—except that these objects will be actual
Person
objects.
defining a reference type
The first thing you need to do is create the constructor, which is shown here:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Your first thought might be that what you have here is simply a function, and you'd be right. It's
not until you start defining the properties and methods that it becomes something more than a
function. This is in contrast to some programming languages, which have a more formal way of
defining types.
Note
Typically, a reference type is defined with an uppercase letter. Doing so
makes it easy to differentiate a function from a reference type easily and quickly.
Inside the function, notice the use of the
this
variable. Once again, it literally means “this object,”
and it is the only way to access the object that is being created. So to create the
firstName
and
lastName
properties, you write the following code:
this.firstName = firstName;
this.lastName = lastName;
Now you need to define
getFullName()
and
greet()
methods. You can define them inside of the
constructor, but it is more efficient to define them on
Person
's
prototype
, like this:
Person.prototype.getFullName = function() {
return this.firstName + " " + this.lastName;
};
Person.prototype.greet = function(person) {
alert("Hello, " + person.getFullName() +
". I'm " + this.getFullName());
};
The first thing you notice is
Person.prototype
. Remember from Chapter 4 that functions are
objects in JavaScript, and in this chapter you learned that objects have properties and methods. So
it's easy to assume that functions have properties and methods.