3

In the following learners piece of code, call to foo() below was expected to return "bar1" based on the following understanding that in non-strict mode, the this keyword binds to global based on the default binding rule and undefined in strict mode.

function foo(){
  console.log(this.bar);
}
var bar = 'bar1';
var o1 = {bar: 'bar2', foo: foo};
var o2 = {bar: 'bar3', foo: foo};

foo();       // expect 'bar1' - default binding
o1.foo();    // expect 'bar2' - implicit binding
o2.foo();    // expect 'bar3' - implicit binding

However the on calling foo() I'm getting undefined in console. o1.foo() and o2.foo() behaves as expected based on implicit binding. It seems to me that the binding is working as expected, but the bar variable is never stuck on to global.

I ran the script in node 6

> node script.js
undefined
bar2
bar3

Note:- in browser it gives the expected output.

user3206440
  • 4,749
  • 15
  • 75
  • 132
  • 2
    Your `var bar` is not a global variable, but one in the module's implicit scope. Create it without `var` by explicit assignment, or as `global.bar = 'bar1';` – Bergi Aug 31 '16 at 05:10
  • @Rayon - I don't think that is true - there is global obj in node – user3206440 Aug 31 '16 at 05:10
  • @Bergi – I was not aware of that.. Just executed that code in `cmd` and realized that... Deleted my comment.. – Rayon Aug 31 '16 at 05:13

1 Answers1

2

That's because Node modules run in their own closure, so var bar is actually creating a local variable, not a global one.

Node modules are essentially wrapped like this, so they don't run in the global scope.

function (exports, require, module, __filename, __dirname) { /*your code here*/
}

If you were to do bar = 'bar1'; without the var, or global.bar = 'bar1'; you would create a global variable, and you would get your expected output. Don't actually do that in production though, it pollutes the global space.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • makes sense. One follow-up question. Running the code (same as in OP) in strict mode `"using strict"` gives `TypeError: Cannot read property 'bar' of undefined` – user3206440 Aug 31 '16 at 05:24
  • @user3206440 Yes, the implicit `this` is `undefined` in strict mode, and trying to access a property of undefined throws a `TypeError`. – Alexander O'Mara Aug 31 '16 at 05:25