Diode
Diode

Reputation: 25135

Node JS simple function and `this`

We know that in a Chrome window, when the following code is executed

function test(){
    console.log("function is " + this.test);
}
test();

test is added as a function to window object and it shows

function is function test(){
    console.log("function is " + this.test);
}

in console.

When I put the same code in a file sample.js, and execute using node

nodejs$  node sample.js

it is giving

function is undefined

But when I execute the same code directly in node terminal

nodejs$ node
> function test(){
...         console.log("function is " + this.test);
...     }test();

it shows the same output as browser.

Can anybody explain why this happens and how V8 engine executes a Javascript file ? Would like to know more about it, so if possible please provide links to articles and tutorials on this.

Upvotes: 0

Views: 792

Answers (3)

Tamil
Tamil

Reputation: 5358

Basically as @igl mentioned modules have their own scope

You can assume that node wraps all your module code around a

(function () {
// Your module code goes here
})() 

before executing it. Hence creating a local scope for the module itself.

Reason: It will prevent global scope from getting polluted

Scenario: Say you have module sample which has a test function in it and also another module say sample2 which also has a test function in it. If node hadn't created a local scope for your sample and sample2 then either of the test function would have overridden the other.

Also you need to understand node is interested only in module.exports object of a module

Example:

var sample = 'you will not see me in global object';
hai = 'but i will be there';
test = function () {
   console.log("function is ",  this.test);
}
console.log(global);
test();

Here there is no var infront of hai and test hence it becomes global as the same in a browser window scope. Now try executing the above in your local node instance

 hai: 'but i will be there',
 test: [Function] }
function is  function () {
    console.log("function is ",  this.test);
}

You should see a big list of global object's properties and also your test function's definition. sample won't be there in the list but

Upvotes: 0

mike
mike

Reputation: 7177

Good question!

Using the following code in sample.js

function is function test(){
    console.log("this is " + this);
}
test();

Chrome shows that at the time, test() is running in the scope of DOMWindow:

this is [object DOMWindow]

Node shows that at the time, test() is running in the scope of the object global:

this is [object global]

But since test() has been defined as part of the module sample.js, this.test is undefined at the time test() is running.

Upvotes: 0

igl
igl

Reputation: 106

The global object in Node behaves differently. A module has its own scope. You can only create a true global using "global.foo = true"

Upvotes: 1

Related Questions