1

I have made an object in javascript its running fine but in the end of every statement it is saying "Undefined".Here's my javascript.

<script>
    window.onload=function(){
        function sports(sportsname, country, player, difficulty){
             this.sportsname = sportsname;
             this.country = country;
             this.player = player;
             this.difficulty = difficulty; 
             this.hissportstaste = sportstaste;
        }

        var Cricket = new sports("Cricket", "Pakistan", "Shahid Afridi", "Difficult");
        var Football = new sports("Football", "Spain", "David Villa", "Difficult");
        var Tennis = new sports("Tennis", "Switzerland", "Roger Federer", "Difficult");

        function sportstaste(){
            if(this.country == "Pakistan"){
                document.write(this.player + " Is the best and he is a " + this.sportsname + " Player");
            }
            if(this.country == "Spain"){
                document.write(this.player + " Is the best and he is a " + this.sportsname + " Player");
            }
            if(this.country == "Switzerland"){
                document.write(this.player + " Is the best and he is a " + this.sportsname + " Player");
            }
        }
        document.write(Cricket.hissportstaste());
        document.write("<br>");
        document.write(Football.hissportstaste());
        document.write("<br>");
        document.write(Tennis.hissportstaste());
        document.write("<br>");
    }

    </script> 

And the output that its giving is.

Shahid Afridi Is the best and he is a Cricket Playerundefined
David Villa Is the best and he is a Football Playerundefined
Roger Federer Is the best and he is a Tennis Playerundefined

I am expecting this output.

Shahid Afridi Is the best and he is a Cricket Player
David Villa Is the best and he is a Football Player
Roger Federer Is the best and he is a Tennis Player

Any idea??

Linga
  • 10,379
  • 10
  • 52
  • 104
user3443160
  • 106
  • 9

1 Answers1

4

Change

document.write(Football.hissportstaste());

to

Football.hissportstaste();

and the same for the similar calls : your functions returns nothing (undefined) and already writes to the document.

But you should try to completely avoid document.write, this functions has very specific uses (it can't be used once the document is loaded), you should learn to change the DOM instead (see this for example).

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758