0

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?

Dinesh
  • 3,652
  • 2
  • 25
  • 35

3 Answers3

2

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.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

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

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

Replace

document.write(p1.showX());

with

p1.showX();

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