zolibra
zolibra

Reputation: 532

Node.js and javascript interpreter different?

For below code, in Javascript i got output : The Window

var name = "The Window";
var object = {
   name : "My Object",
       getNameFunc : function(){
         return function(){
           return this.name;
         };
       }
     };
console.log(object.getNameFunc()());

but for Node.js , i got below output : undefined

i was confused that , is Node.js use the difference interpreter with javascript?

Upvotes: 4

Views: 2711

Answers (2)

zs2020
zs2020

Reputation: 54543

this points to the owner which makes the call. In your example, since you used the self executing function object.getNameFunc()(), then the owner is the window object in the browser.

In node, if you run it in the node console, you will see 'The Window', if you run the script using the command >node xxx.js, you will see undefined.

Upvotes: 0

xdazz
xdazz

Reputation: 160923

In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable.

So in the global scope, when you run var name = "The Window";, it is same with window.name = "The window";.

In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

That's the reason you can't get name in nodejs.

Upvotes: 4

Related Questions