subclass - JavaScript - 创建派生类

标签 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
  2. Cat.prototype = new Pet();Dog.prototype = new Pet(); 何时执行。

最佳答案

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

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

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

关于subclass - JavaScript - 创建派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12518584/

相关文章:

uilabel - 子类化 UILabel

c# - 在 C# 4.0 中,是否可以从泛型类型参数派生类?

c++ - std::bind() - 从派生类的成员函数中获取基保护成员函数

c++ - 错误 : Invalid base class C++

oop - 在 Fortran 中调用派生类型数组的类型绑定(bind)过程

javascript - 使用 new 和存储在变量中的 ES6 类的 Node 出现错误

Python 子类化 - 如何更新另一个类属性使用的类属性

c# - 如何检查对象是否派生自接口(interface)?

c# - 使用派生类将抽象类序列化为 XML。 System.InvalidOperationException < Class xmlns="/> 不是预期的

java - 为子类的私有(private)属性赋值