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
183 views
in Technique[技术] by (71.8m points)

javascript - What is the 'global' object in NodeJS

I've just seen a weird behaviour of the this keyword in NodeJS environment. I'm listing them with code. I've run this codes with NodeJS v6.x, with a single JavaScript file.

While testing with one line of code as follows, whether with or without the 'use strict' statement, this points to an empty object {}.

console.log(this)

But, when I'm running the statement within a self executing function like,

(function(){
  console.log(this);
}());

It's printing a really big object. Seems to me the Global execution context object created by NodeJS environment.

And while executing the above function with a 'use strict' statement, expectedly it's printing undefined

(function(){
  'use strict';

  console.log(this);
}());

But, while working with browser (I've tested only with Chrome), the first three examples yield the window object and the last one gave undefined as expected.

The behaviour of the browser is quite understandable. But, in case of NodeJS, does it not create the execution context, until I'm wrapping inside a function?

So, most of the code in NodeJS runs with an empty global object?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

While in browsers the global scope is the window object, in nodeJS the global scope of a module is the module itself, so when you define a variable in the global scope of your nodeJS module, it will be local to this module.

You can read more about it in the NodeJS documentation where it says:

global

<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.js this is different. The top-level scope is not the global scope; var something inside an Node.js module will be local to that module.

And in your code when you write:

  • console.log(this) in an empty js file(module) it will print an empty object {} referring to your empty module.
  • console.log(this); inside a self invoking function, this will point to the global nodeJS scope object which contains all NodeJS common properties and methods such as require(), module, exports, console...
  • console.log(this) with strict mode inside a self invoking function it will print undefined as a self invoked function doesn't have a default local scope object in Strict mode.

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

...