Q:What gets alerted in the piece of code below?

function foo() {
  this.moo = "bar";
}

function roo() {
  foo();
  alert(moo);
}

A: bar.

Function roo knows the value of variable moo which was defined in function foo, even though we have not defined moo anywhere in roo’s context nor at the global level. So, how does roo know the value of variable moo? Welcome to the world of JavaScript “this” keyword. In JavaScript, “this” always refers to the owning object. So, when function foo() is called from roo, parser sees the variable moo declared as this.moo = “bar”. So, now who owns the function foo? It is the global object. So, moo gets attached to the global object because of which roo can now access the value of moo.

Let us revisit the code with a few changes.

function foo() {
  this.moo = "loo";
}

function roo() {
  new foo();
  alert(moo);
}

Now you get an error saying moo is not defined. This is because, now you are no longer executing the function foo() directly.You are creating an object of type foo. So, now moo no longer belongs to the global object. It belongs to the object created out of foo.

This can be a bit intimidating in the beginning. But as you work through JavaScript I am sure you will start loving it :).

Advertisements