2011-11-18 59 views
-1

我剛剛開始使用Javascript上的OOP。我對編程世界很陌生。你能幫我下面的代碼嗎?我的文本編輯器在'else'塊上顯示語法錯誤。Javascript中對象和方法的錯誤

function Dog(name, breed, weight) { 
    this.name = name; 
    this.breed = breed; 
    this.weight = weight; 
    this.bark = function() { 
     if (this.weight > 25) alert(this.name + " says Woof") 
    } else { 
     alert(this.name + " says Poof"); 
    } 
} 

var fido = new Dog("Fido", "Mixed", 38); 

fido.bark(); 
+2

'汪汪汪汪()' - >'fido.bark();'和語法檢查器可能會抱怨後缺少分號第一次警報。 –

+0

噢,你錯過了一個開頭'''if'(...)'後'' –

+0

非常感謝@Munim – chhantyal

回答

1

試試這個

function Dog(name, breed, weight){ 
this.name = name; 
this.breed = breed; 
this.weight = weight; 
this.bark = function(){ 
     if (this.weight > 25){ 
      alert(this.name + " says Woof"); 
     } 
     else { 
      alert(this.name + " says Poof"); 
     } 
    }; 
} 

var fido = new Dog("Fido", "Mixed", 38); 

fido.bark(); 
1
if (this.weight > 25) 
    alert(this.name + " says Woof") 
} 
else { 
    alert(this.name + " says Poof"); 
} 

你如果{

2

你缺少不打開一個{if (this.weight > 25)以及一個.bark();

    之間 fido

    function Dog(name, breed, weight){ 
        this.name = name; 
        this.breed = breed; 
        this.weight = weight; 
        this.bark = function(){ 
         if (this.weight > 25){ 
          alert(this.name + " says Woof") 
         } else { 
          alert(this.name + " says Poof"); 
         } 
        } 
    } 
    
    var fido = new Dog("Fido", "Mixed", 38); 
    fido.bark(); 
    
  1. 您需要適當的縮進到更容易看到這樣的東西。
  2. 我認爲你的運行時抱怨其他問題,因爲它在函數之外而不是「附加」到if,因爲缺少括號。
  3. 也許JavaScript不是學習編程的語言。你只是玩弄學習,或者你嘗試完成某些事情?
+0

我需要在幾天內學習jQuery(我有日常工作,HTML/CSS直到這一天)。所以,我試圖在Javascript上做一些基礎。 – chhantyal

+2

狗應該也可以有一個右括號。 – Frode

+0

@Frode:對,謝謝! –

0
if (this.weight > 25) 
    alert(this.name + " says Woof") 
} 

就是它出了問題,你就錯過一個{。它應該是:

if (this.weight > 25) 
{ 
    alert(this.name + " says Woof") 
} 
1
function Dog(name, breed, weight){ 
this.name = name; 
this.breed = breed; 
this.weight = weight; 
this.bark = function(){ 
if (this.weight > 25){ 
alert(this.name + " says Woof") 
} 
else { 
alert(this.name + " says Poof"); 
} 
} 
} 

var fido = new Dog("Fido", "Mixed", 38); 

fido bark(); 
相關問題