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?

5
  • 3
    Don't just link to your code, put it here. Commented Oct 23, 2013 at 19:48
  • just updated the question with the code. please have a look Commented Oct 23, 2013 at 19:50
  • 3
    First thing to do: stop using document.write(). Commented Oct 23, 2013 at 19:51
  • document.write does not just "call" your own function, it prints the returned result. Commented Oct 23, 2013 at 19:52
  • you could replace your document.write with console.log() and view the output in your console window. then reveal what you really want by appending the values to a variable, which then gets appended to the DOM. Commented Oct 23, 2013 at 19:59

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

Replace

document.write(p1.showX());

with

p1.showX();

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.