Nazerke
Nazerke

Reputation: 2098

Adding property to object, defining it and immediately logging it returns undefined

Why does immediately invoking newly added property to the object return "undefined"? Going through the compiling and running process would be great. Example line 3 console.log:

function foo(baz) {
    this.baz = "baz";
    console.log(baz); //why does this print undefined?
}

var baz = new foo();

Upvotes: 0

Views: 27

Answers (1)

Tushar
Tushar

Reputation: 87203

Because you need to use this.baz to access the variable you've added earlier.

this inside the foo() refers to the foo function. But, when you log baz it'll be searched on the window(global) object, since it is not defined in the foo().

So, your statement is like:

console.log(window.baz);

Since baz is not defined, it'll log undefined.

Demo

function foo() {
  this.baz = "baz";
  alert(this.baz);
}

var baz = new foo();

Demo of global baz

var baz = 'foo';

function foo() {
  console.log(this);
  this.baz = "baz";
  alert(baz);
  // Same as alert(window.baz);
}

var baz = new foo();


Updated question:

Sorry I forgot to add parameter. I've edited the question – Nazerke

function foo(baz) {
    this.baz = "baz";
    console.log(baz); //why does this print undefined?
}

var baz = new foo();

Because you haven't passed any parameter to the foo() when creating new object using new, you get baz as undefined in the foo().

Demo

function foo(baz) {
  this.baz = baz;
  alert(baz);
}

var baz = new foo('Magic!');

Upvotes: 2

Related Questions