-3

 function foo() {
      this.baz = "baz";
      console.log(this.bar + " " + baz);
    }
    
    var bar = "bar";
    var baz = new foo(); // "undefined undefined"
    
    foo(); // "bar baz"

When i am running above function the output is undefined undefined. I don't understand why the values of both bar and baz are not showing in console log.

but when i am calling simply foo(), output in console is "bar baz". why is like that?

21stnomad
  • 26
  • 1
  • 5
  • 1
    `this.bar` doesn't exist, but `this.baz` does - typo? Anyway, while the function is executing, `baz` hasn't been assigned the same function's return value (or, in this case, the new object instance) yet. – Niet the Dark Absol Apr 13 '17 at 11:44
  • 1
    Shouldn't `(this.bar + " " + baz)` be `(this.baz + " " + bar)`? – Rajesh Apr 13 '17 at 11:44
  • First, `this` will be new instance being created which don't have `bar` on it, second, `baz` is actually `undefined`. – Tushar Apr 13 '17 at 11:45
  • Why would you *expect* this to work in the first place and *what* do you expect it to output exactly? – deceze Apr 13 '17 at 11:46
  • there is no `bar` property and `baz` variable. – gurvinder372 Apr 13 '17 at 11:48
  • @mplungjan, I think this should have been closed as a typo instead – Rajesh Apr 13 '17 at 11:51
  • 1
    @Rajesh I sort of agree, but the duplicate gives much more information which is sorely needed in this case or we will see another question in a minute – mplungjan Apr 13 '17 at 11:55

2 Answers2

1

this.bar is not defined, perhaps you meant this.baz?

baz is not defined because you are printing within the constructor function. while it's running the global baz variable is still undefined.

thedude
  • 9,388
  • 1
  • 29
  • 30
-1

Its easy. Just because you have problem with scopes.

See...

function foo() {
      this.baz = "baz";
      console.log(bar + " " + this.baz);
    }
    
    var bar = "bar";
    var baz = new foo();
Kryštof Řeháček
  • 1,965
  • 1
  • 16
  • 28
  • Please do not answer a typographical mistake – Rajesh Apr 13 '17 at 11:46
  • @Rajesh How do you know that this is typographical mistake ? and do you know the difference between a typographical mistake and wrong syntax ? – Suresh Atta Apr 13 '17 at 11:47
  • @ANS `Wrong syntax`??? Please explain. I might have misunderstood question. Also I was not the voter on your answer. – Rajesh Apr 13 '17 at 11:50
  • 1
    @Rajesh I don't really care about votes. Have them enough and Wrong Syntax is writing writing `baz` instead of `this.baz` – Suresh Atta Apr 13 '17 at 11:51
  • @ANS I still don't see how that is wrong syntax. Isn't this what is called as typographical mistake? Typing `this` in front of wrong variable – Rajesh Apr 13 '17 at 11:54
  • Both you're right. @Rajesh means that he just made a typo with `bar` and `baz`, but @ANS means that he did not write `this.baz`. – Kryštof Řeháček Apr 13 '17 at 11:57