0

以下代码来自Example Second Edition 的 JavaScript,它运行良好。我无法完全理解使用构造函数,在我评论 Dog.prototype.constructor=Dog 和 Cat.prototype.constructor=Cat 行之后,我发现它也很有效,我得到了相同的结果,为什么?谢谢!

<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>
4

1 回答 1

0

只是为了让子类被识别为子类。它不会影响构造函数或对象本身的功能,但会影响某种类型的检查。这是一个例子。

留在:

var d = new Dog();
d.constructor // Dog, all is good

遗漏:

var d = new Dog();
d.constructor // Pet? This dog isn't a dog?
于 2012-05-31T02:02:40.267 回答