1

When I run this code in node, the function foo prints undefined. But if I run the same code in the Chrome or Firefox console I get the right output (oops, global). Can anyone clarify why?

function foo() {
  console.log(this.a);
}
function doFoo(fn) {
  // `fn` is just another reference to `foo`
  fn(); // <-- call-site!
}
var obj = {
  a: 2,
  foo: foo
};
var a = "oops, global"; // `a` also property on global object
doFoo(obj.foo); // "oops, global"
faintsignal
  • 1,828
  • 3
  • 22
  • 30
tecnocrata
  • 901
  • 1
  • 8
  • 19

1 Answers1

2

In browsers, global variables become properties of the window object. And when a function is called without a context, the context also defaults to the window object. Since you're calling foo() without supplying a context, this.a is treated as window.a, which is the global variable.

Node.js has a global object called global, but global variables are not made properties of that object. See Does node.js have equivalent to window object in browser. this.a is treated as global.a, but this is undefined because the variable declaration doesn't assign to it.

Barmar
  • 741,623
  • 53
  • 500
  • 612