为什么我在使用document.write()时未定义?

时间:2017-06-05 07:26:04

标签: javascript oop

为什么我在浏览器中使用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

2 个答案:

答案 0 :(得分:1)

您试图在不返回值的函数上使用document.write,而是自己执行document.writePerson.greeting()应返回一个值,以便在调用document.write(person2.greeting())时使用它。

它应该是这样的:

function Person (name) {
    this.name = name;
    this.greeting = function() {
        return ("Hello " + name +  " Go rock the industry!!");
          ▲
    };
}

答案 1 :(得分:1)

您需要更新greeting函数以返回字符串,而不是自己调用document.write()

目前,greeting函数正在调用document.write()然后隐式返回值undefined

评估表达式时

personX.greeting() + "<br/>"

评估为

undefined + "<br/>"

并且,根据JavaScript字符串连接的规则,undefined首先被转换为字符串"undefined",然后与下一个值连接。

编辑:

如果您对探索property getter functions感兴趣,还可以重构为

function Person (name) {
    this.name = name;
    Object.defineProperty(this, 'greeting', {
        get: function() {
            return "Hello " + this.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>");

请注意我们如何访问计算值personX.greeting,就像它只是一个字符串属性一样。

根据您的环境等,如果您可以使用ES2015 +语法,您可以使用

获得相同的结果
class Person {

  constructor(name) {
    this.name = name;
  }

  get greeting() {
    return `Hello ${this.name} Go rock the industry!!`
  }
}

let person1 = new Person('Sara');
let person2 = new Person('Bob');

document.write(person1.name + "<br>");
document.write(person1.greeting + "<br>");
document.write(person2.name + "<br>");
document.write(person2.greeting + "<br>");