HTML and CSS Reference
In-Depth Information
EXAMPLE
8.16
<html>
<head><title>Creating a subclass</title>
<script type="text/javascript">
1
function Pet(){
//
Base Class
2
var owner = "Mrs. Jones";
var gender = undefined;
3
this.setOwner = function(who) { owner=who;};
this.getOwner = function(){ return owner; }
4
this.setGender = function(sex) { gender=sex; }
this.getGender = function(){ return gender; }
}
5
function Cat(){}
//
subclass constructor
6
Cat.prototype = new Pet();
7
Cat.prototype.constructor=Cat;
8
Cat.prototype.speak=function speak(){
return("Meow");
};
9
function Dog(){}
; /
subclass constructor
10
Dog.prototype= new Pet();
Dog.prototype.constructor=Dog;
Dog.prototype.speak = function speak(){
return("Woof");
};
</script>
</head>
<body><big>
<script>
11
var cat = new Cat;
var dog = new Dog;
12 cat.setOwner("John Doe");
cat.setGender("Female");
13 dog.setGender("Male");
14 document.write("The cat is a "+
cat.getGender()
+ " owned by "
+
cat.getOwner()
+" and it says " +
cat.speak()
);
document.write("<br>The dog is a "+
dog.getGender()
+""+
" owned by " +
dog.getOwner()
+ " and it says "
+
dog.speak()
);
</script>
</big>
</body>
</html>
EXPLANATION
1
The constructor function called
Pet
will define the properties and methods for a
Pet
class. The Pet constructor creates a class of Pets and is the base class for the
Dog
and
Cat
classes defined later in the program.
2
Local variables are set for the object. All Pet objects will have an owner and a gen-
der. The default value for the owner is Mrs. Jones. The gender is
undefined.