user3443160
user3443160

Reputation: 106

Javascript object undefined keyword in the end of output statement

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??

Upvotes: 1

Views: 54

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

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).

Upvotes: 4

Related Questions