【问题标题】:JavaScript -Creating derived classJavaScript - 创建派生类
【发布时间】:2012-09-13 04:06:26
【问题描述】:
<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();

【问题讨论】:

  • 我重新格式化了您的代码并添加了缺少的 html 标签,您能否再解释一下您的问题?
  • 为什么 JavaScript 在大括号后面加上分号。通常大括号出现在句末之后,我的第二个问题是
  • 为什么 JavaScript 在大括号后面加上分号。通常花括号出现在句末之后,我的第二个问题是在创建 Cat 对象之后将执行下一行。

标签: subclass derived-class


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2015-08-10
    相关资源
    最近更新 更多