繁体   English   中英

使用JavaScript的意外输出

[英]Unexpected output with Javascript

这是位于http://jsfiddle.net/QWXf4/1/的JavaScript代码段

var x = 5;

function PartyWithoutX(person) {
    // This property will go to window and pollute the global object
    dance = function (person) {
        document.write("Hello " + person.getFullName() + ", Welcome to the Party.");
    };

    this.showX = function () {
        // This will change the global x variable
        x = 25;
        document.write("Value of x is " + x);
    };
}

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

Person.prototype.getFullName = function () {
    return this.firstName + " " + this.lastName;
};

var dinesh = new Person("Dinesh", "Singh");

var p1 = new PartyWithoutX(dinesh);

document.write(window.dance(dinesh) + "; Enjoy!!");
document.write("<br/>");
document.write(p1.showX());
document.write("<br/>");
document.write(window.x);
document.write("<br/>");

您可以检查的输出是

Hello Dinesh Singh, Welcome to the Party.undefined; Enjoy!!
Value of x is 25undefined
undefined

我期待

Hello Dinesh Singh, Welcome to the Party; Enjoy!!
Value of x is 25
undefined

为什么在输出中出现“ Party.undefined”和“ 25undefined”。

这里发生了什么?

当你做

document.write(p1.showX());

你在做

document.write("Value of x is " + x);

在那之后

document.write(undefined);

因为p1.showX()返回undefined

但是正如Pointy所指出的, 您根本不应该使用document.write ,尤其是在文档加载之后

您正在将这些函数调用的结果传递给document.write() 他们什么都不返回,所以您得到那些“未定义”的结果。

更换

document.write(p1.showX());

p1.showX();

因为第一个打印的是pi1.showX()的结果,该结果未定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM