6

I have updated my Node.Js into version 7.6.0 and running google chrome version 57.0 on the other hand.

When I run this snippet of javascript code, I get two different result like below:

    'use strict'
    
    var obj = {
        id: "awesome",
        cool: function coolFn() {
            console.log(this.id);
        }
    };
    var id = "not awesome";
    obj.cool(); //awsome
    
    setTimeout(obj.cool, 100);

result on chrome:

awesome
not awesome

result on node.js:

awesome
undefined

Recording to https://nodejs.org/en/docs/es6/ I even used the --harmony flag but the result of node.js didn't change.

Cœur
  • 32,421
  • 21
  • 173
  • 232
Ali Khatami
  • 328
  • 1
  • 15

1 Answers1

5

When node runs your file, it's treated as a module, and the docs say it's effectively wrapped thusly:

(function (exports, require, module, __filename, __dirname) {
  // Your module code actually lives in here
});

This means that var id = "not awesome"; is scoped within that module wrapper, and isn't created as a property on the global object.

When timers fire, this is set to the global object. So in the browser, where var id is on the global scope, you see it, whereas in node, it's undefined.

If we wrap the code in a function in the browser, you see the same result:

(function() {
    'use strict'
    
    var obj = {
        id: "awesome",
        cool: function coolFn() {
            console.log(this.id);
        }
    };
    var id = "not awesome";
    obj.cool(); //awsome
    
    setTimeout(obj.cool, 100);
})();
James Thorpe
  • 28,613
  • 5
  • 64
  • 82
  • thanks for your complete answer, I was wondering if I could get the same result as the browser on node.js according to : https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/apC.md how can I access module scope like the global scope? – Ali Khatami Mar 22 '17 at 16:26
  • @Ali It really depends on exactly what it is you're trying to achieve. Judicious use of `.bind` should do the job, but you might be better off with a follow up question. – James Thorpe Mar 22 '17 at 16:30