Javascript NodeJS 中的“全局”对象是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43627622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:03:24  来源:igfitidea点击:

What is the 'global' object in NodeJS

javascriptnode.jsscopethisglobal

提问by Arnab Das

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

我刚刚this在 NodeJS 环境中看到了关键字的奇怪行为。我用代码列出它们。我用NodeJS v6.x, 用一个JavaScript文件运行了这个代码。

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

在用如下一行代码进行测试时,无论有没有'use strict'语句, this 都指向一个空对象{}

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

它正在打印一个非常大的对象。在我看来,环境创建的全局执行上下文对象NodeJS

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

并且在使用'use strict'语句执行上述函数时,预计它正在打印undefined

(function(){
  'use strict';

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

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

但是,在使用浏览器时(我只用 测试过Chrome),前三个示例产生了window对象,最后一个undefined如预期的那样给出。

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?

浏览器的行为是可以理解的。但是,在 的情况下NodeJS,它不会创建执行上下文,直到我包装在一个函数中?

So, most of the code in NodeJSruns with an empty globalobject?

那么,大多数代码NodeJS运行时都带有一个空的globalobject?

采纳答案by cн?dk

While in browsers the global scope is the windowobject, 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.

在浏览器中,全局范围是window对象,而在 nodeJS 中,模块的全局范围是模块本身,因此当您在 nodeJS 模块的全局范围内定义变量时,它将是该模块的本地变量。

You can read more about it in the NodeJS documentationwhere it says:

您可以在NodeJS 文档中阅读有关它的更多信息,其中说:

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.

全球的

<Object> The global namespace object.

在浏览器中,顶级作用域是全局作用域。这意味着在浏览器中,如果您在全局范围 var 中,则某些内容将定义一个全局变量。在 Node.js 中这是不同的。顶级作用域不是全局作用域;Node.js 模块中的 var 某些内容将是该模块的本地内容。

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, thiswill 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 modeinside a self invoking function it will print undefinedas a self invoked function doesn't have a default local scope object in Strict mode.
  • console.log(this)在一个空的 js 文件(模块)中,它会打印一个{}指向你的空模块的空对象。
  • console.log(this);在自调用函数中,this将指向全局 nodeJS 作用域对象,该对象包含所有 NodeJS 公共属性和方法,例如require(), module, exports, console...
  • console.log(this)在自调用函数中使用严格模式,它将打印undefined为自调用函数在严格模式下没有默认的本地范围对象。

回答by Willem van der Veen

Value of thisin a node module:

的值this的节点模块中:

thisin NodeJS global scopeis the current module.exports object, not the global object. This is different from a browser where the global scope is the global windowobject. Consider the following code executed in Node:

this在NodeJS全局范围内是当前的 module.exports 对象,而不是全局对象。这与全局范围是全局window对象的浏览器不同。考虑在 Node 中执行的以下代码:

console.log(this);    // logs {}

module.exports.foo = 5;

console.log(this);   // log { foo:5 }

First we log an empty object because there are no values in module.exportsin this module. Then we put fooon the module.exportsobject, when we then again log thiswe can see that it now logs the updated module.exportsobject.

首先我们记录一个空对象,因为module.exports这个模块中没有值。然后,我们把foo该上module.exports的对象,当我们再登录this我们可以看到,它现在记录更新的module.exports对象。

How can we access the globalobject:

我们如何访问global对象:

We can access the globalobject in node using the globalkeyword:

我们可以global使用global关键字访问节点中的对象:

console.log(global);

The globalobject exposes a variety of useful properties about the environment. Also this is the place where functions as setImmediateand clearTimeoutare located.

global对象公开了有关环境的各种有用属性。这也是功能setImmediate和所在的地方clearTimeout

回答by Frank Roth

Very interesting:

很有意思:

var JSON = require('circular-json');

console.log('1) ' + JSON.stringify(this, null, 2));

(function(){
    console.log('2) ' + JSON.stringify(this, null, 2));
}());

(function(){
  'use strict';
   console.log('3) ' + JSON.stringify(this, null, 2));
}());

will produce:

将产生:

1) {}


2) {
  "global": "~",
  "process": {
    "title": "node",
    "version": "v6.9.1",
    "moduleLoadList": [
      "Binding contextify",
      "Binding natives",
      "NativeModule events",
      "NativeModule util",
      "Binding uv",
      "NativeModule buffer",
      "Binding buffer",
      "Binding util",
      "NativeModule internal/util",
      "NativeModule timers",
      "Binding timer_wrap",
      "NativeModule internal/linkedlist",
      "NativeModule assert",
      "NativeModule internal/process",
      "Binding config",
      "NativeModule internal/process/warning",
      "NativeModule internal/process/next_tick",
      "NativeModule internal/process/promises",                                                                                                              
      "NativeModule internal/process/stdio",                                                                                                                 
      "Binding constants",                                                                                                                                   
      "NativeModule path",                                                                                                                                   
      "NativeModule module",                                                                                                                                 
      "NativeModule internal/module",                                                                                                                        
      "NativeModule vm",                                                                                                                                     
      "NativeModule fs",                                                                                                                                     
      "Binding fs",                                                                                                                                          
      "NativeModule stream",                                                                                                                                 
      "NativeModule _stream_readable",                                                                                                                       
      "NativeModule internal/streams/BufferList",                                                                                                            
      "NativeModule _stream_writable",                                                                                                                       
      "NativeModule _stream_duplex",                                                                                                                         
      "NativeModule _stream_transform",                                                                                                                      
      "NativeModule _stream_passthrough",                                                                                                                    
      "Binding fs_event_wrap",                                                                                                                               
      "NativeModule console",                                                                                                                                
      "Binding tty_wrap",                                                                                                                                    
      "NativeModule tty",                                                                                                                                    
      "NativeModule net",                                                                                                                                    
      "NativeModule internal/net",                                                                                                                           
      "Binding cares_wrap",                                                                                                                                  
      "Binding tcp_wrap",                                                                                                                                    
      "Binding pipe_wrap",                                                                                                                                   
      "Binding stream_wrap",                                                                                                                                 
      "Binding signal_wrap"                                                                                                                                  
    ],                                                                                                                                                       
    "versions": {                                                                                                                                            
      "http_parser": "2.7.0",                                                                                                                                
      "node": "6.9.1",                                                                                                                                       
      "v8": "5.1.281.84",                                                                                                                                    
      "uv": "1.9.1",                                                                                                                                         
      "zlib": "1.2.8",                                                                                                                                       
      "ares": "1.10.1-DEV",                                                                                                                                  
      "icu": "57.1",                                                                                                                                         
      "modules": "48",                                                                                                                                       
      "openssl": "1.0.2j"                                                                                                                                    
    },                                                                                                                                                       
    "arch": "x64",                                                                                                                                           
    "platform": "linux",                                                                                                                                     
    "release": {                                                                                                                                             
      "name": "node",                                                                                                                                        
      "lts": "Boron",                                                                                                                                        
      "sourceUrl": "https://nodejs.org/download/release/v6.9.1/node-v6.9.1.tar.gz",
      "headersUrl": "https://nodejs.org/download/release/v6.9.1/node-v6.9.1-headers.tar.gz"
    },
    "argv": [
      "/usr/local/bin/node",
      "/home/froth/freelancer-projects/thistest.js"
    ],
    "execArgv": [],
    "env": {
      "NVM_DIR": "/home/froth/.nvm",
      "LD_LIBRARY_PATH": "/opt/opencascade/lib",
      "CSF_UnitsDefinition": "/opt/opencascade/src/UnitsAPI/Units.dat",
      "CSF_GraphicShr": "/opt/opencascade/lib/libTKOpenGl.so",
      "CSF_EXCEPTION_PROMPT": "1",
      "LANG": "de_DE.UTF-8",
      "PROFILEHOME": "",
      "DISPLAY": ":0",
      "SHELL_SESSION_ID": "09b6f0f3b1d94c5f8aba3f8022075677",
      "NODE_PATH": "/usr/lib/node_modules",
      "COLORTERM": "truecolor",
      "NVM_CD_FLAGS": "",
      "MOZ_PLUGIN_PATH": "/usr/lib/mozilla/plugins",
      "CSF_IGESDefaults": "/opt/opencascade/src/XSTEPResource",
      "CSF_XCAFDefaults": "/opt/opencascade/src/StdResource",
      "XDG_VTNR": "1",
      "PAM_KWALLET5_LOGIN": "/tmp/kwallet5_froth.socket",
      "CSF_STEPDefaults": "/opt/opencascade/src/XSTEPResource",
      "XDG_SESSION_ID": "c2",
      "CSF_XSMessage": "/opt/opencascade/src/XSMessage",
      "USER": "froth",
      "DESKTOP_SESSION": "/usr/share/xsessions/awesome",
      "GTK2_RC_FILES": "/home/froth/.gtkrc-2.0",
      "PWD": "/home/froth/freelancer-projects",
      "HOME": "/home/froth",
      "XDG_SESSION_TYPE": "x11",
      "CSF_PluginDefaults": "/opt/opencascade/src/StdResource",
      "XDG_DATA_DIRS": "/usr/local/share/:/usr/share/:/var/lib/snapd/desktop",
      "NVM_IOJS_ORG_MIRROR": "https://iojs.org/dist",
      "KONSOLE_DBUS_SESSION": "/Sessions/1",
      "XDG_SESSION_DESKTOP": "",
      "CSF_StandardDefaults": "/opt/opencascade/src/StdResource",
      "CSF_StandardLiteDefaults": "/opt/opencascade/src/StdResource",
      "MMGT_CLEAR": "1",
      "KONSOLE_DBUS_WINDOW": "/Windows/1",
      "CSF_UnitsLexicon": "/opt/opencascade/src/UnitsAPI/Lexi_Expr.dat",
      "GTK_MODULES": "canberra-gtk-module",
      "MAIL": "/var/spool/mail/froth",
      "NVM_RC_VERSION": "",
      "CSF_XmlOcafResource": "/opt/opencascade/src/XmlOcafResource",
      "TERM": "xterm-256color",
      "SHELL": "/bin/bash",
      "KONSOLE_DBUS_SERVICE": ":1.23",
      "XDG_SESSION_CLASS": "user",
      "XDG_SEAT_PATH": "/org/freedesktop/DisplayManager/Seat0",
      "XDG_CURRENT_DESKTOP": "",
      "QT_LINUX_ACCESSIBILITY_ALWAYS_ON": "1",
      "KONSOLE_PROFILE_NAME": "Shell",
      "CASROOT": "/opt/opencascade",
      "NVM_NODEJS_ORG_MIRROR": "https://nodejs.org/dist",
      "COLORFGBG": "15;0",
      "XDG_SEAT": "seat0",
      "SHLVL": "2",
      "LANGUAGE": "",
      "WINDOWID": "29360134",
      "LOGNAME": "froth",
      "DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1000/bus",
      "XDG_RUNTIME_DIR": "/run/user/1000",
      "CSF_MDTVTexturesDirectory": "/opt/opencascade/src/Textures",
      "XAUTHORITY": "/home/froth/.Xauthority",
      "XDG_SESSION_PATH": "/org/freedesktop/DisplayManager/Session1",
      "PATH": "/home/froth/.gem/ruby/2.3.0/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/snap/bin:/usr/lib/jvm/default/bin:/opt/opencascade/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl",
      "CSF_LANGUAGE": "us",
      "CSF_SHMessage": "/opt/opencascade/src/SHMessage",
      "OLDPWD": "/home/froth",
      "_": "/usr/local/bin/node"
    },
    "pid": 4658,
    "features": {
      "debug": false,
      "uv": true,
      "ipv6": true,
      "tls_npn": true,
      "tls_alpn": true,
      "tls_sni": true,
      "tls_ocsp": true,
      "tls": true
    },
    "_needImmediateCallback": false,
    "execPath": "/usr/local/bin/node",
    "debugPort": 5858,
    "_events": {
      "SIGWINCH": [
        null,
        null
      ]
    },
    "_eventsCount": 4,
    "domain": null,
    "_exiting": false,
    "config": {
      "target_defaults": {
        "cflags": [],
        "default_configuration": "Release",
        "defines": [],
        "include_dirs": [],
        "libraries": []
      },
      "variables": {
        "asan": 0,
        "debug_devtools": "node",
        "force_dynamic_crt": 0,
        "gas_version": "2.23",
        "host_arch": "x64",
        "icu_data_file": "icudt57l.dat",
        "icu_data_in": "../../deps/icu-small/source/data/in/icudt57l.dat",
        "icu_endianness": "l",
        "icu_gyp_path": "tools/icu/icu-generic.gyp",
        "icu_locales": "en,root",
        "icu_path": "deps/icu-small",
        "icu_small": true,
        "icu_ver_major": "57",
        "node_byteorder": "little",
        "node_enable_d8": false,
        "node_enable_v8_vtunejit": false,
        "node_install_npm": true,
        "node_module_version": 48,
        "node_no_browser_globals": false,
        "node_prefix": "/",
        "node_release_urlbase": "https://nodejs.org/download/release/",
        "node_shared": false,
        "node_shared_cares": false,
        "node_shared_http_parser": false,
        "node_shared_libuv": false,
        "node_shared_openssl": false,
        "node_shared_zlib": false,
        "node_tag": "",
        "node_use_bundled_v8": true,
        "node_use_dtrace": false,
        "node_use_etw": false,
        "node_use_lttng": false,
        "node_use_openssl": true,
        "node_use_perfctr": false,
        "node_use_v8_platform": true,
        "openssl_fips": "",
        "openssl_no_asm": 0,
        "shlib_suffix": "so.48",
        "target_arch": "x64",
        "uv_parent_path": "/deps/uv/",
        "uv_use_dtrace": false,
        "v8_enable_gdbjit": 0,
        "v8_enable_i18n_support": 1,
        "v8_inspector": true,
        "v8_no_strict_aliasing": 1,
        "v8_optimized_debug": 0,
        "v8_random_seed": 0,
        "v8_use_snapshot": true,
        "want_separate_host_toolset": 0
      }
    },
    "stdout": {
      "connecting": false,
      "_hadError": false,
      "_handle": {
        "bytesRead": 0,
        "_externalStream": {},
        "fd": 9,
        "writeQueueSize": 0,
        "owner": "~process~stdout"
      },
      "_parent": null,
      "_host": null,
      "_readableState": {
        "objectMode": false,
        "highWaterMark": 16384,
        "buffer": {
          "head": null,
          "tail": null,
          "length": 0
        },
        "length": 0,
        "pipes": null,
        "pipesCount": 0,
        "flowing": null,
        "ended": false,
        "endEmitted": false,
        "reading": false,
        "sync": true,
        "needReadable": false,
        "emittedReadable": false,
        "readableListening": false,
        "resumeScheduled": false,
        "defaultEncoding": "utf8",
        "ranOut": false,
        "awaitDrain": 0,
        "readingMore": false,
        "decoder": null,
        "encoding": null
      },
      "readable": false,
      "domain": null,
      "_events": {},
      "_eventsCount": 3,
      "_writableState": {
        "objectMode": false,
        "highWaterMark": 16384,
        "needDrain": false,
        "ending": false,
        "ended": false,
        "finished": false,
        "decodeStrings": false,
        "defaultEncoding": "utf8",
        "length": 0,
        "writing": false,
        "corked": 0,
        "sync": false,
        "bufferProcessing": false,
        "writecb": null,
        "writelen": 0,
        "bufferedRequest": null,
        "lastBufferedRequest": null,
        "pendingcb": 1,
        "prefinished": false,
        "errorEmitted": false,
        "bufferedRequestCount": 0,
        "corkedRequestsFree": {
          "next": null,
          "entry": null
        }
      },
      "writable": true,
      "allowHalfOpen": false,
      "destroyed": false,
      "_bytesDispatched": 6,
      "_sockname": null,
      "_writev": null,
      "_pendingData": null,
      "_pendingEncoding": "",
      "server": null,
      "_server": null,
      "columns": 84,
      "rows": 84,
      "_type": "tty",
      "fd": 1,
      "_isStdio": true
    },
    "stderr": {
      "connecting": false,
      "_hadError": false,
      "_handle": {
        "bytesRead": 0,
        "_externalStream": {},
        "fd": 11,
        "writeQueueSize": 0,
        "owner": "~process~stderr"
      },
      "_parent": null,
      "_host": null,
      "_readableState": {
        "objectMode": false,
        "highWaterMark": 16384,
        "buffer": {
          "head": null,
          "tail": null,
          "length": 0
        },
        "length": 0,
        "pipes": null,
        "pipesCount": 0,
        "flowing": null,
        "ended": false,
        "endEmitted": false,
        "reading": false,
        "sync": true,
        "needReadable": false,
        "emittedReadable": false,
        "readableListening": false,
        "resumeScheduled": false,
        "defaultEncoding": "utf8",
        "ranOut": false,
        "awaitDrain": 0,
        "readingMore": false,
        "decoder": null,
        "encoding": null
      },
      "readable": false,
      "domain": null,
      "_events": {},
      "_eventsCount": 3,
      "_writableState": {
        "objectMode": false,
        "highWaterMark": 16384,
        "needDrain": false,
        "ending": false,
        "ended": false,
        "finished": false,
        "decodeStrings": false,
        "defaultEncoding": "utf8",
        "length": 0,
        "writing": false,
        "corked": 0,
        "sync": true,
        "bufferProcessing": false,
        "writecb": null,
        "writelen": 0,
        "bufferedRequest": null,
        "lastBufferedRequest": null,
        "pendingcb": 0,
        "prefinished": false,
        "errorEmitted": false,
        "bufferedRequestCount": 0,
        "corkedRequestsFree": {
          "next": null,
          "entry": null
        }
      },
      "writable": true,
      "allowHalfOpen": false,
      "destroyed": false,
      "_bytesDispatched": 0,
      "_sockname": null,
      "_writev": null,
      "_pendingData": null,
      "_pendingEncoding": "",
      "server": null,
      "_server": null,
      "columns": 84,
      "rows": 84,
      "_type": "tty",
      "fd": 2,
      "_isStdio": true
    },
    "stdin": {
      "connecting": false,
      "_hadError": false,
      "_handle": {
        "bytesRead": 0,
        "_externalStream": {},
        "fd": 12,
        "writeQueueSize": 0,
        "owner": "~process~stdin",
        "reading": false
      },
      "_parent": null,
      "_host": null,
      "_readableState": {
        "objectMode": false,
        "highWaterMark": 0,
        "buffer": {
          "head": null,
          "tail": null,
          "length": 0
        },
        "length": 0,
        "pipes": null,
        "pipesCount": 0,
        "flowing": null,
        "ended": false,
        "endEmitted": false,
        "reading": false,
        "sync": false,
        "needReadable": true,
        "emittedReadable": false,
        "readableListening": false,
        "resumeScheduled": false,
        "defaultEncoding": "utf8",
        "ranOut": false,
        "awaitDrain": 0,
        "readingMore": false,
        "decoder": null,
        "encoding": null
      },
      "readable": true,
      "domain": null,
      "_events": {},
      "_eventsCount": 4,
      "_writableState": {
        "objectMode": false,
        "highWaterMark": 0,
        "needDrain": false,
        "ending": false,
        "ended": false,
        "finished": false,
        "decodeStrings": false,
        "defaultEncoding": "utf8",
        "length": 0,
        "writing": false,
        "corked": 0,
        "sync": true,
        "bufferProcessing": false,
        "writecb": null,
        "writelen": 0,
        "bufferedRequest": null,
        "lastBufferedRequest": null,
        "pendingcb": 0,
        "prefinished": false,
        "errorEmitted": false,
        "bufferedRequestCount": 0,
        "corkedRequestsFree": {
          "next": null,
          "entry": null
        }
      },
      "writable": false,
      "allowHalfOpen": false,
      "destroyed": false,
      "_bytesDispatched": 0,
      "_sockname": null,
      "_writev": null,
      "_pendingData": null,
      "_pendingEncoding": "",
      "server": null,
      "_server": null,
      "isRaw": false,
      "isTTY": true,
      "fd": 0
    },
    "argv0": "node",
    "mainModule": {
      "id": ".",
      "exports": {},
      "parent": null,
      "filename": "/home/froth/freelancer-projects/thistest.js",
      "loaded": false,
      "children": [
        {
          "id": "/home/froth/freelancer-projects/node_modules/circular-json/build/circular-json.node.js",
          "exports": {},
          "parent": "~process~mainModule",
          "filename": "/home/froth/freelancer-projects/node_modules/circular-json/build/circular-json.node.js",
          "loaded": true,
          "children": [],
          "paths": [
            "/home/froth/freelancer-projects/node_modules/circular-json/build/node_modules",
            "/home/froth/freelancer-projects/node_modules/circular-json/node_modules",
            "/home/froth/freelancer-projects/node_modules",
            "/home/froth/node_modules",
            "/home/node_modules",
            "/node_modules"
          ]
        }
      ],
      "paths": [
        "/home/froth/freelancer-projects/node_modules",
        "/home/froth/node_modules",
        "/home/node_modules",
        "/node_modules"
      ]
    }
  },
  "console": {}
}


3) undefined

In 3)thisis undefinedas it is not autoboxed to an object in strict mode. That means that there is no root object in this context. If you do not use strict mode then your code is boxed by a parent scope.As you can see in the output, within nodejs there is lot of information about node internal stuff.

3)this 中未定义的,因为它不会在严格模式下自动装箱到对象。这意味着在此上下文中没有根对象。如果您不使用严格模式,那么您的代码会被父作用域装箱。正如您在输出中看到的,在 nodejs 中,有很多关于节点内部内容的信息。

In 1)the output is an empty object because in the top-level code in a node module, this is the equivalent to module.exports and module.exports is empty in this example.

1)输出中是一个空对象,因为在节点模块的顶级代码中,这等效于 module.exports 并且在此示例中 module.exports 为空。

回答by Nirus

To start with documentationon Global context in node environment

从节点环境中的全局上下文文档开始

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.

在浏览器中,顶级作用域是全局作用域。这意味着在浏览器中,如果您在全局范围 var 中,则某些内容将定义一个全局变量。在 Node.js 中这是不同的。顶级作用域不是全局作用域;Node.js 模块中的 var 某些内容将是该模块的本地内容。

Each JS file is treated as a module. Node automatically wraps the code of a JS file in a self IIFE with exports, require, module, __filename, __dirnameas parameters to the function.

每个 JS 文件都被视为一个模块。Node 会自动将 JS 文件的代码包装在 self IIFE 中,并将其exports, require, module, __filename, __dirname作为函数的参数。

Below is the screenshot of execution context using node-debug

下面是使用执行上下文的屏幕截图 node-debug

node-debug

节点调试

If you run the below code, prints truewhich means thisrefers to exportsin node.js. Best explained in this answer.

如果你运行下面的代码,打印出true这意味着 在 node.js 中是thisexports。最好在这个答案中解释。

console.log(this === exports);

Which means at execution the code is wrapped something similar as below in Node.js separating your code from global context using a wrapper function context.

这意味着在执行时,代码在 Node.js 中被包装了类似于下面的内容,使用包装器函数 context将您的代码与全局上下文分开。

  var context = (function (exports, require, module, __filename, __dirname) {
       console.log(this) //This is my code
  });

  var module = {exports:{}};
   context.apply(module.exports, [module.exports, require, module, "FILE_NAME", "DIR_NAME"]);


Answer to the next point refer this documentationcompletely:

对下一点的回答完全参考本文档

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

与其他语言相比,函数的 this 关键字在 JavaScript 中的行为略有不同。严格模式和非严格模式也有一些区别。

so when you execute this code

所以当你执行这段代码时

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

prints the globalobject and in use strictmode prints undefined

打印global对象并在use strict模式下打印undefined



Remember:

记住:

In Browser the function is not wrapped by IIFE/wrapper function context as in node, its directly executed on windowobject. Hence the calling context varies for Node.js and Browser.

在浏览器中,该函数不像在节点中那样被 IIFE/包装器函数上下文包装,而是直接在window对象上执行。因此,调用上下文因 Node.js 和浏览器而异。

Also read this.

也读这个