Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - What is the root object in Node.js

You may know the global object in Node.js:

{Object} The global namespace object.

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. 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.

Now I stumbled over the root object which seems to be documented nowhere.

Though it seems that I can use root the same way as global:

test1.js

foo = 'bar'; // foo is defined in the global scope (no var in front of foo)

test2.js

require('./test1.js');
console.log(root.foo);

In the shell:

$ node test2.js
bar

When I inspect global and root in the shell they look the same. Try:

$ node
> global
...
> root
...

So it seems that root is the same as global. But why the redundancy? Why is root not documented? Is it deprecated?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is exactly the same as global.

There are a few undocumented properties like this. They date from early days of node but were left in to maintain backwards-compatibility and there is no pressing need to remove them.

You shouldn't use them in any new code, as they could be removed at any future time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...