bulb
bulb

Reputation: 178

New keyword in JS

I have been looking at the new keyword in JS. I understand this means that the this keyword is now created in the object. One thing I don't understand is how inside the testNew function baz is undefined.

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

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

As this would now be attached to the new object would this.baz and baz not be the same reference?

Upvotes: -1

Views: 89

Answers (3)

Nisfan
Nisfan

Reputation: 746

You are accessing local variable with this code ... " " + baz, there is no local variable 'baz' is defined.

It should be

this.bar + " " + this.baz
                 ^^^

Upvotes: 1

abadalyan
abadalyan

Reputation: 1235

Let's take a look at this line,

var baz = new testNew();

What's happening here is:

  1. baz variable is created with value undefined
  2. testNew function is called, this inside of it is a new object, but baz is still undefined
  3. testNew finishes and returns the newly created object which is then assigned to baz

Upvotes: 2

Alberti Buonarroti
Alberti Buonarroti

Reputation: 459

function testNew()
{
    this.baz = "baz";
    console.log("this.bar + \" \"  + baz: ", this.bar + " " + baz); // this fails
    console.log("this.baz: ", this.baz);
}

var bar = "bar";
var baz = new testNew();
console.log("baz: ", baz);

You are trying to access this.bar, which does not exist inside your testNew() function. You defined bar on a global namespace and can call it using bar.
Also baz is not defined at the moment you try to call it since you are referencing the global baz which you are currently initializing with your testNew() function

Upvotes: 1

Related Questions