简体   繁体   中英

Unexpected output with Javascript

Here is a JavaScript code snippet at http://jsfiddle.net/QWXf4/1/

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/>");

The output as you can check is

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

I was expecting

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

Why do I get "Party.undefined" and "25undefined" in the output.

Whats going on here?

When you do

document.write(p1.showX());

you're doing

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

and after that doing

document.write(undefined);

because p1.showX() returns undefined .

But as Pointy pointed, you should not use document.write at all, especially after the document was loaded .

You're passing the results of those function calls to document.write() . They don't return anything, so you get those "undefined" results.

Replace

document.write(p1.showX());

with

p1.showX();

Because the first prints the results of pi1.showX() which is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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