Ali Khatami Ali Khatami -4 years ago 85
Javascript Question

Why there is defferent outputs in running JavaScript on web and nodejs?

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.

Answer Source

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);
})();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download