为什么我在使用document.write()时在浏览器中未定义?为什么我在使用document.write()时未定义?
<script type="text/javascript">
function Person (name) {
this.name = name;
this.greeting = function() {
document.write("Hello " + name + " Go rock the industry!!");
};
}
var person1 = new Person("Sara");
var person2 = new Person("Bob");
document.write(person1.name + "<br>");
document.write(person1.greeting() + "<br>");
document.write(person2.name + "<br>");
document.write(person2.greeting() + "<br>");
</script>
在浏览器中我得到这个输出:
Sara
Hello Sara Go rock the industry!!undefined
Bob
Hello Bob Go rock the industry!!undefined
'document.write'返回'undefined'达到同样的效果。你在'document.write'里面使用'document.write'。相反,只需从函数'return'Hello'+ name ...'返回字符串即可。 – Tushar
如果你在'Person'原型上定义了'greetings'方法,并且将name命名为'this.name',而不是使用'document.write'在body上添加内容,那会更好。 – Tushar
@Tushar你的意思是这个'function Person(name){ \t \t this.name = name; \t \t this.greeting = function(){ \t \t \t document.write(“Hello”+ this.name +“Go the industry the industry !!”“); \t \t}; \t} \t变种PERSON1 =新的Person(” 萨拉 “); \t文件撰写(person1.name +”
“); \t person1.greeting();' –