무엇'글로벌'체에 및 라이브러리

나는've 그 이상한 행동을의키워드가 및 라이브러 environment. 나는'm 로 그들을 나열하는 코드입니다. 나는've 실행 코드와 함께및 라이브러 v6.x,하나의``자바 스크립트 파일입니다.

을 테스트하는 동안 한 줄의 코드를 다음과 같이 여부,함께 또는없이'사용하여 엄격한',성명이 포인트 빈 개체{}.

console.log(this)

하지만,때 나는'm 문을 실행하는 내에서 실행하는 자와 같은 기능,

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

It's 를 인쇄하는 정말 큰 개체입니다. 보 글로벌 실행 컨텍스트 객체에 의해 만들어및 라이브러리환경이다.

고 실행되는 동안 위의 기능을 가진'사용하여 엄격한'문 expectedly it's 쇄undefined

(function(){
  'use strict';

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

하지만 작업하는 동안,브라우저(I've 테스트만을 가진Chrome),첫 번째 세 가지 예수익의창의객체고 마지막 중 하나에게 준undefined으로 예상된다.

행동의 브라우저히 이해할 수 있습니다. 하지만,의 경우에는및 라이브러리,그것은 만들지 실행 컨텍스까지,나는'm 감싸 안는 기능입니까?

그래서 대부분의 코드에서라이브러리에 해당하는 개발용으로 실행 빈글로벌object?

질문에 대한 의견 (1)
해결책

는 브라우저에서는 글로벌 범위의창의객체가 및 라이브러리의 글로벌 범위 모듈은 모듈을 자체,그래서를 정의할 때는 변수에는 전역의 범위 및 라이브러리 모듈,그것은 로컬을 이 모듈이 있습니다.

에 대해 자세히 알아볼 수 있습에서 그것및 라이브러리 설명서는 곳에 그것을 말합니다:

글로벌

<Object>글로벌 네임스페이스 객체입니다.

브라우저에서,최고 수준의 범위는 글로벌 범위가 있습니다. 즉 브라우저에서 당신이'시에 글로벌 범위 var 뭔가를 정의합니다 글로벌 변수입니다. 에 Node.js 이것은 다릅니다. 최고 수준의 범위 하지 않은 글로벌 범위;var 가 내부에 있는 Node.js 모듈 지역을 하는 모듈이 있습니다.

과에서 당신의 코드를 작성할 때:

-console.로그(이)빈 js 파일(모듈)그것을 인쇄할 것입 빈 개체{}참조 빈 모듈이 있습니다. -console.로그(this);안에 각자를 호출하여 기능,을 가리키는 글로벌 및 라이브러리 범위 객체를 포함하는 모든 및 라이브러 일반적인 속성과 같은 방법require(),모듈,exports,콘솔... -console.로그(이)엄격한 모드안에 각자 함수를 호출하여 그것은 인쇄undefined으로 호출되는 자기능지 않't 는 기본 지역 개체 범위에엄격한 모드.

해설 (0)

값이에서 노드 모듈:

에서 라이브러리에 해당하는 개발용글로벌 범위은 현재 모듈이 있습니다.수출 개체하지 않 글로벌 객체입니다. 이것은 다른 브라우저에서는 글로벌 범위는 글로벌창의객체입니다. 다음 코드를 참조하십시오에서 실행 노드:

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

module.exports.foo = 5;

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

먼저 우리를 로그에 emty 개체 없기 때문에 값이에서 모듈이 있습니다.수출이 모듈이 있습니다. 그런 다음 우리는foo에서 모듈이 있습니다.수출객체을 때,우리는 그런 다음 다시 로그인우리는 볼 수 있습니다 그것은 이제 로그를 업데이트된 모듈이 있습니다.수출개체입니다.

어떻게 접속할 수 있는글로벌개체:

우리에 액세스할 수 있는글로벌개체 노드를 사용하는글로벌키워드:

console.log(global);

글로벌개체 노출에 유용한 다양한 속성에 대한 환경입니다. 또한 이 기능으로setImmediateclearTimeout있습니다.

해설 (1)

매우 흥미로운:

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));
}());

생산됩니다:

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

에서3)이은**undefined**로 autoboxed 개체에 엄격한 모드입니다. 는 없다는 것을 의미한 루트 객체에서 이러한 맥락이다. 을 사용하지 않는 경우 엄격한 모드는 다음의 코드가 박스에 의해 부모 범위가 있습니다.당신이 볼 수 있는 출력에서,및 라이브러리에 많은 정보에 대한 노드가 내부 물건입니다.

에서1)의 출력은 비어 있기 때문에 객체에서 최고 수준의 코드 노드 모듈,이에 상응하는 모듈이 있습니다.수출 모듈에 있습니다.수출입 빈에서 이 예입니다.

해설 (0)

을 시작으로문서에서는 글로벌 콘텍스트에 노 환경

브라우저에서,최고 수준의 범위는 글로벌 범위가 있습니다. 즉,브라우저에서 당신이'시에 글로벌 범위 var 뭔가를 정의합니다 전역 변수입니다. 에 Node.js 이것은 다릅니다. 최고 수준의 범위는 글로벌 범위;var 가 내부에 있는 Node.js 모듈이 될 지역을 하는 모듈이 있습니다.

각 JS 파일로 처리 모듈. 노드를 자동으로 감싸 코드의 JS 파일에 자기 인생으로수출을 필요로,모듈,__름,__dirname매개 변수로 기능입니다.

아래 스크린샷의 실행 컨텍스트가 사용하는노드를 디버깅

실행하는 경우 아래 코드는,인쇄진정한 의미하는이것은의미수출`in node.js. 최 설명했다정답.

console.log(this === exports);

는 의미에서 실행 코드를 감싸는 유사한 무언가에서 아래와 같이 Node.js 분리하는 코드에서는 글로벌 콘텍스트를 사용하여래퍼 기능은 컨텍스트.

  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"]);

응답을 다음 포인트 참조 이 문서]4완전히:

function's 이 키워드를 조금 다르게 동작합에서 JavaScript 를 비교하는 기타 언어입니다. 그것에는 또한 몇 가지 사이의 차이는 엄격한 모드와 비 엄격한 모드입니다.

그래서 이 코드를 실행할 때

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

인쇄하는글로벌개체고에서사용은 엄격한모드 인쇄undefined


을 기억하십시오:

브라우저에서 기능이 포장되지 않습으로 인생/래퍼 기능은 컨텍스트에서 노드의 그것의 직접 실행창의객체입니다. 따라서 호출되는 상황에 따라 다릅 Node.js 고 브라우저입니다.

또한 읽기.

해설 (0)