0

Can someone please explain why in the following code we get output: "wwww":

this.kuki="wwww";

function Ninja()
{
}
Ninja.prototype ={boogie:{kuki:"111",woogie:this.kuki} };
var k= new Ninja();
alert(k.boogie.woogie);//wwww

whereas in the following code we get an output of undefined:

this.kuki="wwww";

function Ninja()
{
  this.boogie={kuki:"111",woogie:this.kuki} ;
}
var k= new Ninja();
alert(k.boogie.woogie);//undefined

?

mary
  • 869
  • 5
  • 13
  • 26
  • 1
    In one example you use `woogie:this.kuki` inside a function and in the other you do not. – Quentin Sep 20 '17 at 17:41
  • Well, I was about to answer but Quentin closed the question pointing you to a frankly biblical answer. Long story short: outisde of a function, `this` references the `Window` object (browser), or the `Global` object (node) – salezica Sep 20 '17 at 17:43
  • oh, so since the second one is inside the function, the "this" is defined by the object created. whereas in the first since it's not inside the function the scope is a global scope? – mary Sep 20 '17 at 17:43
  • @mary: Yes, because the function was called via `new`. – T.J. Crowder Sep 20 '17 at 17:51
  • This question shouldn't have been closed, it's like someone asking "why is this behaving that way" and someone answering "go read this book". BTW @T.J.Crowder's explanation is correct. – doubleOrt Sep 22 '17 at 19:56

0 Answers0