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.
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.
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.
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.
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.
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);
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With