The following code is from JavaScript by Example Second Edition, it works well.
I can’t understand completely the usage constructor, after I comment the line Dog.prototype.constructor=Dog and Cat.prototype.constructor=Cat
I find it work wells too and I get the same result, why? Thanks!
<html>
<head><title>Creating a subclass</title>
<script type="text/javascript">
function Pet(){ // Base Class
var owner = "Mrs. Jones";
var gender = undefined;
this.setOwner = function(who) { owner=who;};
this.getOwner = function(){ return owner; }
this.setGender = function(sex) { gender=sex; }
this.getGender = function(){ return gender; }
}
function Cat(){} //subclass constructor
Cat.prototype = new Pet();
Cat.prototype.constructor=Cat;
Cat.prototype.speak=function speak(){
return("Meow");
};
function Dog(){};//subclass constructor
Dog.prototype= new Pet();
Dog.prototype.constructor=Dog;
Dog.prototype.speak = function speak(){
return("Woof");
};
</script>
</head>
<body><big>
<script>
var cat = new Cat;
var dog = new Dog;
cat.setOwner("John Doe");
cat.setGender("Female");
dog.setGender("Male");
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>
It’s just so that the subclasses will be recognized as a subclass. It doesn’t impact the functionality of the constructor or object itself, but it does impact a certain kind of type-checking. Here’s an example.
Left in:
Left out: