HTML and CSS Reference
In-Depth Information
class will have a copy of the function code.) In Example 8.6, the
calculate
property is
assigned an inline or anonymous function. Because it is part of the definition of the
Dis-
tance()
constructor, only objects of the Distance class will have access to the method,
thereby encapsulating the method. In previous examples the functions that served as
methods were defined outside of the constructor, making available to any class.
EXAMPLE
8.6
<html>
<head><title>functions</title>
<script type="text/javascript">
1
function Distance(r, t)
{//
Constructor function
2
this.rate = r;
this.time = t;
3
this.calculate=function() { return r * t; }
//
anonymous
}
</script>
</head>
<body>
<script type ="text/javascript">
4
var trip1 = new Distance(50, 1.5)
;
5
var trip2 = new Distance(75, 3.2)
;
6
alert("trip 1 distance: "+
trip1.calculate()
);
alert("trip 2 distance: "+
trip2.calculate()
);
</script>
</body>
</html>
EXPLANATION
1
This is the constructor function for the
Distance
class. It takes two parameters,
r
and
t
, and returns a reference to an object.
2
Properties are assigned to the object. The
this
keyword is a reference to the current
object.
3
When a function is assigned to a property, it is called a method. This is an inline
or anonymous function. It has no name but has been defined and assigned to the
object as a method.
4
A new object called
trip1
is created with the
new
constructor. Two arguments are
passed, the rate (how fast) and the time (in hours). This is the first instance of the
Distance
class.
5
Another object,
trip2
, is created and sends different argument values.
6
See Figure 8.7. The method called
calculate()
is invoked for each object. The alert
box displays the value returned from the
calculate()
method; that is, the distance
traveled.