2012-03-20 102 views
0

我目前在學習面向對象的Javascript,但似乎警報不起作用。這裏有什麼問題?Javascript警告框未顯示

< 

html> 
<head> 
    <script> 

    function professor(name, myLecture){ 
     this.name = name; 
     this.myLecture = myLecture; 
    } 

    professor.prototype.display = function(){ 
     return this.name + " is teaching " + this.myLecture; 
    }; 

    function subjectList(subject){ 
     this.subject = subject; 
    } 

    subjectList.prototype.showAll= function(){ 
      var str = " " ; 
      for(var i = 0 ; i<subject.length; i++) 
      str+= this.subject[i].display(); 
      return str; 
    }; 

    var ListOfSubs = new subjectList([ 
     new professor("Muy","Obprog") 
    ]); 

    alert(ListOfSubs.showAll()); 

    </script> 
    <body> 
    </body> 
</head> 
</html> 
+0

您是否在您使用的瀏覽器中打開了JavaScript調試器並查看是否有錯誤? – 2012-03-20 13:41:17

+0

確保你的javascript沒有錯誤第一(ReferenceError:主題未定義 - 第17行) – Nacho 2012-03-20 13:41:22

+0

使用調試器...我得到的錯誤是'主題未定義' – xandercoded 2012-03-20 13:41:57

回答

2

應該是this.subject.length而不是subject.length

+0

爲什麼使用this.subject.length?而後者呢? – user962206 2012-03-20 13:46:36

+1

''subject''在'showAll''方法中不可見。所以你需要使用''這個'' – Engineer 2012-03-20 13:50:18

0

你需要this.

subjectList.prototype.showAll= function(){ 
      var str = " " ; 
      for(var i = 0 ; i< this.subject.length; i++) // notice this.subject 
      str+= this.subject[i].display(); 
      return str; 
    }; 
+0

爲什麼使用「this」? – user962206 2012-03-20 13:54:00

0

行:

for(var i = 0 ; i<subject.length; i++) 

的錯誤是, 「主題沒有定義」。 將它從subject.length = 更改爲 .subject.length應該可以解決您的問題。

它應該輸出:

Muy is teaching Obprog 
+0

你是怎麼看到這個錯誤的? – user962206 2012-03-20 13:59:13

0

其他你瞭解什麼是錯的與你的js代碼的原因。

來自我的另一個注意。

以前發生異常時,通常不會出現編程警報。

順便說一下,你的身體標記應該是封閉頭標籤後

0

此代碼將你的腳本標籤中工作:

function professor(name, myLecture){ 
     this.name = name; 
     this.myLecture = myLecture; 
    } 

    professor.prototype.display = function(){ 
     return this.name + " is teaching " + this.myLecture; 
    }; 

    function subjectList(subject){ 
     this.subject = subject; 
    } 

    subjectList.prototype.showAll= function(){ 
      var str = " " ; 
      for(var i = 0 ; i<subject.length; i++) 
      str+= this.subject[i].display(); 
      return str; 
    }; 

    var ListOfSubs = new subjectList([ 
     new professor("Muy","Obprog") 
    ]); 

    alert(ListOfSubs.showAll()); 

原因:你的SHOWALL功能您使用主題,這是不存在的,但你的原型的對象有一個叫做主題的成員。因此,而不是i<subject.lengthi<this.subject.length正在解決您的問題。