Arn*_*Das 43 javascript scope global this node.js
我刚刚this在NodeJS环境中看到了关键字的奇怪行为.我用代码列出它们.我NodeJS v6.x用一个JavaScript文件运行这些代码.
在使用以下一行代码进行测试时,无论是否使用该'use strict'语句,都指向一个空对象{}.
console.log(this)
Run Code Online (Sandbox Code Playgroud)
但是,当我在自执行函数中运行语句时,
(function(){
console.log(this);
}());
Run Code Online (Sandbox Code Playgroud)
它正在打印一个非常大的对象.在我看来环境创建的全局执行上下文对象NodeJS.
在使用'use strict'语句执行上述功能时,预计会打印undefined
(function(){
'use strict';
console.log(this);
}());
Run Code Online (Sandbox Code Playgroud)
但是,在使用浏览器(我只测试过Chrome)时,前三个示例产生window对象,最后一个示例undefined按预期方式给出.
浏览器的行为是可以理解的.但是,如果是NodeJS,它不会创建执行上下文,直到我在函数内部包装?
那么,大多数代码NodeJS运行时都是空的全局 object?
cнŝ*_*ŝdk 36
在浏览器中,全局范围是window对象,在nodeJS中,模块的全局范围是模块本身,因此当您在nodeJS模块的全局范围内定义变量时,它将是该模块的本地变量.
您可以在NodeJS文档中阅读更多相关信息,其中包含:
全球
<Object> The global namespace object.在浏览器中,顶级范围是全局范围.这意味着在浏览器中,如果您在全局范围内,var会定义一个全局变量.在Node.js中,这是不同的.顶级范围不是全球范围; Node.js模块中的var内容将是该模块的本地内容.
在你编写的代码中:
console.log(this)在一个空的js文件(模块)中,它将打印一个{}引用空模块的空对象.console.log(this);自调用函数中,this将指向包含了所有常见的NodeJS属性和诸如方法在全球范围内的NodeJS对象require(),module,exports,console...console.log(this)在自调用函数内部使用严格模式,它将undefined作为自调用函数打印,在严格模式下没有默认的本地范围对象.Wil*_*een 13
this的节点模块中:this在NodeJS中,全局范围是当前的module.exports对象,而不是全局对象.这与全局范围是全局window对象的浏览器不同.考虑在Node中执行的以下代码:
console.log(this); // logs {}
module.exports.foo = 5;
console.log(this); // log { foo:5 }
Run Code Online (Sandbox Code Playgroud)
首先我们记录一个emty对象,因为module.exports这个模块中没有值.然后,我们把foo该上module.exports的对象,当我们再登录this我们可以看到,它现在记录更新的module.exports对象.
global对象:我们可以global使用global关键字访问节点中的对象:
console.log(global);
Run Code Online (Sandbox Code Playgroud)
该global对象暴露了有关环境的各种有用属性.这也是功能setImmediate和clearTimeout位置的地方.
很有意思:
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));
}());
Run Code Online (Sandbox Code Playgroud)
将产生:
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,
"_write
在这里我想强调一下 global 的一个属性!
您放在那里的内容也可以直接访问
(请务必检查房产标题和部分)
在携带财产之前!让我们重新定义一下全局吧!
global是nodejs特有的语言关键字,并引用全局命名空间对象
正如其他答案中已经描述的那样!模块中的顶级范围!不是全球性的!并且仅限于该模块!
因此,当您在一个模块中声明变量时,您无法在另一个模块中访问它!
https://nodejs.org/api/globals.html#globals_global
全局命名空间在给定进程中的任何地方都可以访问!在所有模块中!这包括您自己的模块和第三方模块!
控制台在节点 repl 中全局记录将给出以下内容:
Welcome to Node.js v13.14.0.
Type ".help" for more information.
> console.log(global)
<ref *1> Object [global] {
global: [Circular *1],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
setInterval: [Function: setInterval],
setTimeout: [Function: setTimeout] {
[Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
},
queueMicrotask: [Function: queueMicrotask],
clearImmediate: [Function: clearImmediate],
setImmediate: [Function: setImmediate] {
[Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
}
}
undefined
Run Code Online (Sandbox Code Playgroud)
我想带的就是这个!当我探索laravel-mix代码源时,我注意到了这一点!
如果你在全局对象上设置了一些东西!就像一样
global.Hola = { print: () => console.log("Hola") };。然后,您可以在项目代码中的任何位置(多个文件[模块]和整个节点进程代码)直接通过名称访问变量!意思Hola.print()是代替global.Hola.print()!
这是上面示例的节点复制屏幕截图:
> global.Hola = { print: () => console.log('Hola') }
{ print: [Function: print] }
> Hola.print()
Hola
undefined
Run Code Online (Sandbox Code Playgroud)
不错的房产!这就是全局命名空间!
您可以注意到那里定义了诸如clearInteraval、clearTimeout、setInterval、 ...之类的方法!setTimeout我们过去常常通过名称直接访问它们!
这里有一些来自 laravel-mix 代码源的示例!哪里用那个!
如果打开此文件: https://github.com/JeffreyWay/laravel-mix/blob/master/src/components/ComponentRegistrar.js
您注意到导入部分没有!Mix变量都不是Config!但它们被使用并且是代码的一部分!我像:what the heck!
爱莫特代码:
Welcome to Node.js v13.14.0.
Type ".help" for more information.
> console.log(global)
<ref *1> Object [global] {
global: [Circular *1],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
setInterval: [Function: setInterval],
setTimeout: [Function: setTimeout] {
[Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
},
queueMicrotask: [Function: queueMicrotask],
clearImmediate: [Function: clearImmediate],
setImmediate: [Function: setImmediate] {
[Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
}
}
undefined
Run Code Online (Sandbox Code Playgroud)
在第 68 行:(链接在这里Mix)您可以看到类变量的用法!
第 178 行也有同样的事情Config(链接在这里)
当我第一次看到它的时候!并检查导入部分!并使用 github 参考功能(什么都没有)!我曾是What the heck!
后来当我检查Mix.js文件时!还有课!我找到了设置它们的代码!我得到了直觉,然后用谷歌搜索了!
设置全局变量的一个问题是覆盖和冲突!这会导致错误和意外行为,甚至完全崩溃!如果模块不假思索地开始使用它!一个模块会把另一个模块搞砸!就像使用第三方模块时一样!Imagine 模块request将设置Config var!而且你也设置了!甚至另一个第三方模块!他们都依赖它!一个人会把它拧到另一个模块上!
简单地说!我们不应该使用全局变量!不,不!是的!
这一切都取决于!
模块最好不要这样做!这样模块就完全隔离了!而且更加坚固!一般是在某个模块中设置变量!并且每次都导入!使用依赖注入...等
然而,在许多情况下,使用全局命名空间更为灵活!
您可以这样做,不用担心!如果您正在构建服务器!Config对象可以放到全局去!命令行界面工具或脚本!有些进程直接运行!
构建模块时通常不要使用全局作用域!一套!图书馆!一个组件!哪个可以重复使用!(可重用的跨项目!没有全局范围!隔离它)!
例如Laravel mix是一个用于生成 webpack 配置的包!它可以作为 cli 工具和进程运行!
但是,如果Config变量也由 Webpack 或某些社区插件或加载器设置!那么就会因为覆盖而出现问题!
一些简单的事情可以使它更安全,那就是在命名中添加一个域!例如!Mix_Config
从节点环境中的全局上下文文档开始
在浏览器中,顶级作用域是全局作用域。这意味着在浏览器中,如果您在全局范围 var 中,则会定义一个全局变量。在 Node.js 中这是不同的。顶级作用域不是全局作用域;Node.js 模块中的 var 某些内容将是该模块的本地内容。
每个 JS 文件都被视为一个模块。Node 会自动将 JS 文件的代码包装在 self IIFE 中,并将其exports, require, module, __filename, __dirname作为函数的参数。
下面是使用执行上下文的屏幕截图 node-debug
如果你运行下面的代码,打印出true这意味着 在 node.js 中是this指exports。最好在这个答案中解释。
console.log(this === exports);
Run Code Online (Sandbox Code Playgroud)
这意味着在执行时,代码在 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"]);
Run Code Online (Sandbox Code Playgroud)
对下一点的回答完全参考本文档:
与其他语言相比,函数的 this 关键字在 JavaScript 中的行为略有不同。严格模式和非严格模式也有一些区别。
所以当你执行这段代码时
(function(){
console.log(this);
}());
Run Code Online (Sandbox Code Playgroud)
打印global对象并在use strict模式下打印undefined
记住:
在浏览器中,该函数不像在节点中那样被 IIFE/包装器函数上下文包装,而是直接在window对象上执行。因此,调用上下文因 Node.js 和浏览器而异。
也读这个。
| 归档时间: |
|
| 查看次数: |
19490 次 |
| 最近记录: |