Java Reference
In-Depth Information
architect's drawings are the template used to build a house. Before you can use your new object type,
you need to defi ne it along with its methods and properties. The important distinction is that when you
defi ne your reference type, no object based on that type is created. It's only when you create an instance
of your reference type using the new keyword that an object of that type, based on your blueprint or
prototype, is created.
Before you start, an important distinction must be made. Many developers refer to reference types as
classes and use the two terms interchangeably. While this is correct for many object-oriented languages
such as Java, C#, and C++, it is not correct for JavaScript. JavaScript has no formal class construct, even
though the logical equivalent, reference types, are fully supported by the language.
It's also important to point out that the built-in objects discussed thus far in this chapter are also refer-
ence types. String, Array, Number, Date, and even Object are all reference types, and the objects you
created are instances of these types.
A reference type consists of three things:
A constructor
Method defi nitions
Properties
A constructor is a method 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 it contains no code. (In that case it'd just be
an empty defi nition.) As with functions, a constructor can have zero or more parameters.
You used methods when you used JavaScript's built-in reference types; now you get the chance to build
your own type to defi ne your own methods performing specifi c tasks. Your reference type will specify
what methods you have and the code that they execute. Again, you have used properties of built-in
objects before and now get to defi ne your own. You don't need to declare your type's properties. You
can simply go ahead and use properties without letting JavaScript know in advance.
Let's create a simple reference type based on the real-world example of a cinema booking system.
Defi ning a Reference Type
Let's start by creating a type for a customer's booking. It will be called CustomerBooking. The fi rst
thing you need to do is create the constructor, which is shown here:
function CustomerBooking (bookingId, customerName, film, showDate)
{
this.customerName = customerName;
this.bookingId = bookingId;
this.showDate = showDate;
this.film = film;
}
You r fi rst thought might be that what you have here is simply a function, and you'd be right. It's not
until you start defi ning 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 defi ning types.
Search WWH ::




Custom Search