Home > Mobile >  Javascript new keyword difference in output
Javascript new keyword difference in output

Time:10-20

Why do I get 2 different output when I run in Chrome -> DevTools -> Sources and when I run in JSFiddle.

The code which I run is as follows

function foo() {
    this.baz = "baz"
    console.log(this.bar   " "   baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)

Output in chrome

undefined [object Object]
baz

Output in JSFiddle

"undefined undefined"
"baz"

Essentially chrome is telling me that baz is an object of type {baz:"baz"} but jsFiddle tells me it is undefined.

enter image description here enter image description here

CodePudding user response:

Are you sure you did not run the same code on chrome twice?

The first time baz is clearly undefined, but if you paste the same code again it has the value you already defined (var baz = new foo();).

CodePudding user response:

When a standard page with that code on it is run the result is undefined undefined and then baz.

Inside the function, baz refers to the outer variable named baz, which is the instance that's being created (but hasn't been created yet - it'll be created after the foo function returns the instance). So, at that moment, it should be undefined.

But, the console is not like a standard webpage; it'll save previous values assigned to variables when you run it again. You must have run the code more than once - in which case, it's like doing

function foo() {
    this.baz = "baz"
    console.log(this.bar   " "   baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)

// you probably cleared the console manually at this point
// before running it again

function foo() {
    this.baz = "baz"
    console.log(this.bar   " "   baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

so the [object Object] you see is from a previous run's instance.

  • Related