B.W
B.W

Reputation: 77

why there are differences for below code runing in browser and nodeJS?

I have below code which I expect the results would be printing 2, 2.

When I run it in nodeJS console, I got undefined, undefined. When I run it in Chrome, I got expected values.

My questions, what differences make this result?

var a = 2; 
function foo(){
    console.log(this.a);
}

(function(){ 
   foo(); 
}()) 

function doFoo(fn){
    fn();
}

var obj ={
    a:3,
    foo:foo
}; 

doFoo(obj.foo);

Upvotes: 0

Views: 23

Answers (1)

slebetman
slebetman

Reputation: 114004

Node.js does not execute code in global scope. Instead each file is wrapped in an IIFE so that each file get their own scope. The difference therefore is that in the browser, var a = 2 is a global variable whereas in node.js var a = 2 is not a global variable.

Since your code prints the global variable a, in the browser that would be 2. In node.js you have not defined a therefore it prints undefined.

To make the code the same change var a = 2 to a = 2 in order to declare a global variable instead of a local variable.

Upvotes: 2

Related Questions