전역 globalThis 속성은 전역 this 값을 가진 전역 객체를 반환합니다.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
구문
globalThis
설명
역사적으로, 서로 다른 JavaScript 환경의 전역 범위에 접근하는건 서로 다른 구문을 필요로 했습니다. 웹에서는 window, self, frames를 사용할 수 있지만, Web Workers에서는 self만 동작합니다. Node.js에서는 아무것도 쓸 수 없고, 대신 global을 사용해야 합니다.
비엄격 모드에서의 함수 내부에서 this를 사용할 수도 있겠지만, 모듈이나 엄격 모드의 함수에서는 undefined를 가리키는 문제가 있습니다. Function('return this')()를 사용하는 방법도 존재하지만, 브라우저의 CSP 등으로 eval()을 사용할 수 없는 환경에선 Function도 이렇게 사용할 수 없습니다.
globalThis 속성은 환경에 무관하게 전역 'this' 값에 접근하는 표준 방법을 제공합니다. 비슷한 속성인 window 및 self와는 다르게 윈도우와 비윈도우 문맥 모두에서 동작을 보장할 수 있습니다. 따라서 코드를 구동하는 환경을 모르더라도 전역 객체에 일관적으로 접근할 수 있습니다.
HTML과 WindowProxy
많은 JavaScript 엔진에서 globalThis는 실제 전역 객체를 가리킬 것이나, 웹 브라우저는 iframe과 윈도우 간 보안 문제로 인하여 전역 객체의 Proxy를 대신 가리키고, 실제 객체는 직접 접근할 수 없습니다. 일반적인 사용처에서는 차이가 없다고 봐도 무방하지만, 알아두는 것은 중요합니다.
이름
self와 global처럼, 다른 인기있던 제안은 기존 코드와의 호환성 문제를 우려해 제외됐습니다. 언어 제안서의 "NAMING" 문서를 방문해 더 자세한 정보를 읽어보세요.
예제
globalThis 없이 현재 환경의 전역 객체를 가져오는 방법 중 유일하게 믿을만한 방법은 Function('return this')() 입니다. 그러나 일부 환경에서는 CSP 위반을 초래하므로 es6-shim은 다음 예제와 같은 검사를 수행합니다.
var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};
var globals = getGlobal();
if (typeof globals.setTimeout !== 'function') {
// no setTimeout in this environment!
}
globalThis를 사용할 수 있으면 환경에 따른 전역 객체 검사는 더 이상 필요하지 않습니다.
if (typeof globalThis.setTimeout !== 'function') {
// no setTimeout in this environment!
}
명세
| Specification | Status | Comment |
|---|---|---|
| globalThis proposal | Stage 3 |
브라우저 호환성
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
globalThis | Chrome Full support 71 | Edge No support No | Firefox Full support 65 | IE No support No | Opera No support No | Safari Full support 12.1 | WebView Android Full support 71 | Chrome Android Full support 71 | Firefox Android Full support 65 | Opera Android No support No | Safari iOS Full support 12.2 | Samsung Internet Android Full support 10.0 | nodejs Full support 12.0.0 |
Legend
- Full support
- Full support
- No support
- No support