簡體   English   中英

Javascript Alert框未顯示

[英]Javascript Alert box is not showing

我目前正在學習面向對象的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>

應該this.subject.length代替subject.length

該行:

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

錯誤是“未定義主題”。 更改為subject.length = this .subject.length應該可以解決您的問題。

它應該輸出:

Muy is teaching Obprog

你需要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;
   };

其他人已通知您有關js代碼出問題的原因。

還有我的一張紙條。

通常,在之前發生異常時,不會發出編程的警報。

順便說一句,您的身體標簽應該在關閉的頭部標簽之后

此代碼將在您的腳本標簽內運行:

 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是修復你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM