Javascript对象未定义关键字在输出语句结束

Javascript object undefined keyword in the end of output statement

本文关键字:输出 语句 结束 关键字 对象 未定义 Javascript      更新时间:2023-09-26

我在javascript中制作了一个对象,它运行良好,但在每个语句的末尾都说"未定义"。这是我的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> 

它给出的输出是。

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

我期待这个输出。

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

任何想法?

变化

document.write(Football.hissportstaste());

Football.hissportstaste();

和类似的调用相同:您的函数不返回任何内容(undefined)并且已经写入文档。

但是你应该尽量避免document.write,这个函数有非常特殊的用途(它不能在文档加载后使用),你应该学会改变DOM(参见这个例子)。