4

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You mean that scope for inner function (returning this.name) is 'global' and not the 'top-level'?
Understood - as module is wrapped with another function, 'top-level' is closure scope.
Per my understanding , the name and the function is in the same module , because they are in the same file.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.