简体   繁体   English

Javascript Alert框未显示

[英]Javascript Alert box is not showing

I am currently learning Object oriented Javascript but it seems that the alert is not working. 我目前正在学习面向对象的Javascript,但似乎警报不起作用。 what is the problem here? 这里有什么问题?

<

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

The line: 该行:

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

The error was that "Subject is not defined". 错误是“未定义主题”。 Changing it from subject.length = this .subject.length should fix your problem. 更改为subject.length = this .subject.length应该可以解决您的问题。

It should output: 它应该输出:

Muy is teaching Obprog

You need this. 你需要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;
   };

Other have informed you about the reason what is wrong with your js-code. 其他人已通知您有关js代码出问题的原因。

One more note from me. 还有我的一张纸条。

Usually an programmed alert will not come up when an exception happens before. 通常,在之前发生异常时,不会发出编程的警报。

And by the way, your body-tag should be after the closing head-tag 顺便说一句,您的身体标签应该在关闭的头部标签之后

This code will work inside your script tag: 此代码将在您的脚本标签内运行:

 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());

Cause: in your showAll function you have used subject, which is not existent, but the object of your prototype has a member called subject. 原因:在showAll函数中,您使用的主题不存在,但原型的对象具有一个称为主题的成员。 So instead of i<subject.length , i<this.subject.length is fixing your problem. 因此,而不是i<subject.lengthi<this.subject.length是修复你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM