2012-09-20 31 views
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();
+1

我重新格式化了您的代碼並添加了缺少的html標籤,請問您能解釋一下您的問題嗎? – nana

+0

爲什麼JavaScript在花括號之後放置了分號。通常大括號出現在句子結尾,我的第二個問題是 – swati16

+0

爲什麼JavaScript在大括號後面放了分號。通常花括號在句子結束後出現,而我的第二個問題是在創建Cat對象之後將執行下一行。 – swati16

回答

1

那麼...... JavaScript不會在你自己的代碼中的任何地方放置分號,寫這個腳本的人就做到了,對嗎? 雖然JavaScript做了什麼,但它會在你錯過的空格中自動插入分號(不是在你的代碼中,至少看不到它,它讀取你的代碼,然後它的行爲就像你在寫代碼的時候自動插入了分號一樣)。這有時會產生意想不到的結果。

我建議在每個語句後面使用分號,如在這個偉大的article中所述。

如果我正確理解你的第二個問題,那麼它是這樣的:
JavaScript基於對象Pet的原型實例化新對象。然後將Cat.prototype指向這個新創建的對象。同樣的事情發生在狗的情況下。