Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is different outputs in running JavaScript on web and nodejs? [duplicate]

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.

like image 300
Ali Khatami Avatar asked Mar 22 '17 15:03

Ali Khatami


People also ask

How does node JS differ from JavaScript?

JavaScript is a proper high-level programming language used to create web scripts whereas Node. js is a run time environment built on google's v8 engine. JavaScript is executed in the browser whereas using Node. js gives us the ability to execute JavaScript outside the browser.

What is the connection between NodeJS and JavaScript?

NodeJS is a cross-platform and opensource Javascript runtime environment that allows the javascript to be run on the server-side. Nodejs allows Javascript code to run outside the browser. Nodejs comes with a lot of modules and mostly used in web development.

Why a node JS code is pretty fast although being written in JavaScript?

Q 4 - Why code written in Node. JS is pretty fast although being written in JavaScript? A - Node. JS internally converts JavaScript code to Java based code and then execute the same.

Is node JS multithreaded or single threaded?

Node JS Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model. Node JS Processing model mainly based on Javascript Event based model with Javascript callback mechanism.


1 Answers

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);
})();
like image 57
James Thorpe Avatar answered Sep 30 '22 17:09

James Thorpe