我已经在javascript中创建了一个运行良好的对象,但在每个语句的最后都是" Undefined"。这是我的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
任何想法??
答案 0 :(得分:4)
更改
document.write(Football.hissportstaste());
到
Football.hissportstaste();
和类似调用相同:您的函数不返回任何内容(undefined
)并且已经写入文档。
但是你应该试着完全避免document.write
,这个函数有非常具体的用途(it can't be used once the document is loaded),你应该学习改变DOM(例如参见this)。 / p>