简体   繁体   中英

List all global variables in Node.js

I'm trying to list all of the global variables, including those refering to built-in objects .

In Chrome's console I can simply type this and get back all the keys, including things like String , Number , etc.

However when I do this in Node.js I get much less:

> Object.keys(this)
[ 'global',
  'process',
  'GLOBAL',
  'root',
  'Buffer',
  'setTimeout',
  'setInterval',
  'clearTimeout',
  'clearInterval',
  'setImmediate',
  'clearImmediate',
  'console',
  'module',
  'require',
  '_' ]
> this.eval
[Function: eval]

Where is this.eval coming from?

The built-in properties of the global object are non-enumerable, so Object.keys doesn't return them. You can use Object.getOwnPropertyNames instead.

The following globals() function will get you global namespace object:

function globals() { return this; }

With it you can list all variables of global namespace anytime you want:

function varsList() {
  return Object.getOwnPropertyNames(globals());
}

You can use the Object.getOwnPropertyNames(this) .As without passing the "this" as argument or parameter referring to Object owner's properties, the getOwnPropertyNames() function won't return anything.

Answering your question as to where the eval comes from check this link out. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM