<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
、//2
、//3
的行的右大括号后面有分号>、//4
和//5
? 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/