user962206
user962206

Reputation: 16137

Javascript Alert box is not showing

I am currently learning Object oriented Javascript but it seems that the alert is not working. 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>

Upvotes: 0

Views: 365

Answers (5)

Lajos Arpad
Lajos Arpad

Reputation: 76631

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. So instead of i<subject.length, i<this.subject.length is fixing your problem.

Upvotes: 0

stefan bachert
stefan bachert

Reputation: 9606

Other have informed you about the reason what is wrong with your js-code.

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

Upvotes: 0

azz
azz

Reputation: 5930

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.

It should output:

Muy is teaching Obprog

Upvotes: 1

Engineer
Engineer

Reputation: 48793

Should be this.subject.length instead of subject.length.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190952

You need 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;
   };

Upvotes: 0

Related Questions