JavaScript - 创建派生类

时间:2012-09-20 18:23:13

标签: subclass derived-class

<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的行中的大括号后面有分号?< / LI>
  2. 何时执行Cat.prototype = new Pet();Dog.prototype = new Pet();

1 个答案:

答案 0 :(得分:1)

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

我建议在每个语句后使用分号,如这篇伟大的article中所述。

如果我理解你的第二个问题,那就是这样的:
Javascript基于对象Pet的原型实例化新的Object。然后将Cat.prototype指向这个新创建的对象。在Dog的情况下也会发生同样的事情。