Reputation: 178
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
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
Reputation: 1235
Let's take a look at this line,
var baz = new testNew();
What's happening here is:
baz
variable is created with value undefinedtestNew
function is called, this
inside of it is a new object, but baz
is still undefinedtestNew
finishes and returns the newly created object which is then assigned to baz
Upvotes: 2
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