Java Reference
In-Depth Information
}
CustomerBooking.prototype.getBookingId = function()
{
return this.bookingId;
}
CustomerBooking.prototype.setBookingId = function(bookingId)
{
this.bookingId = bookingId;
}
Now you have defi ned a
set
and
get
method for each of your four properties:
bookingId
,
film
,
customerName
, and
showDate
. Let's look at how you created one of the methods:
getCustomerName()
.
CustomerBooking.prototype.getCustomerName = function()
{
return this.customerName;
}
The fi rst thing you notice is that this is a very odd way of defi ning a function. On the left you set the
type's prototype property's
getCustomerName
to equal a function, which you then defi ne immediately
afterwards. In fact, JavaScript supplies most reference types with a prototype property, which allows
new properties and methods to be created. So whenever you want to create a method for your type, you
simply write the following:
typeName.prototype.methodName = function(method parameter list)
{
// method code
}
You've created your type, but how do you now create new objects based on it?
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
CustomerBooking
, you'd write this:
var firstBooking = new
CustomerBooking(1234, “Robert Smith”,”Raging Bull”, “25 July 2004 18:20”);
var secondBooking = new
CustomerBooking(1244, “Arnold Palmer”,”Toy Story”, “27 July 2004 20:15”);
Here, as with a
String
object, you have created two new objects and stored them in variables,
firstBooking
and
secondBooking
, but this time it's a new object based on the
CustomerBooking
type.
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.