2
<html><head><script>
function Pet(){                                        // Base Class
    var owner = "Mrs. Jones";
    var gender = undefined;
    this.setOwner = function(who) { owner=who; };        //1
    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");                                      //2
    };                                                   //3

function Dog(){};                                        //4     
Dog.prototype= new Pet();
Dog.prototype.constructor=Dog;
Dog.prototype.speak = function speak(){
    return("Woof");
    };                                                   //5

</script></head>
<body><script>

var cat = new Cat;
var dog = new Dog;
cat.setOwner("John Doe");
cat.setGender("Female");
dog.setGender("Male");
document.write(
     "<br>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></body>
  1. //1为什么在上面的代码中标记为、、、//2//3的行的右花括号后有//4分号//5
  2. 何时将Cat.prototype = new Pet();Dog.prototype = new Pet(); 执行。
4

1 回答 1

2

嗯... JavaScript 不会自己在代码中的任何位置放置分号,编写脚本的人会这样做,对吗?然而,JavaScript 所做的是在你错过的空格中自动插入分号(不在你的代码中,至少不可见。它读取你的代码,然后它的行为就像你在编写它时有那些自动插入的分号一样)。这有时会产生意想不到的结果。

我建议在每条语句后使用分号,如这篇精彩的文章中所述

如果我正确理解了您的第二个问题,那么它是这样的:
Javascript 根据对象 Pet 的原型实例化新对象。然后将 Cat.prototype 指向这个新创建的对象。在 Dog 的情况下也会发生同样的事情。

于 2012-09-20T19:01:34.320 回答