어떻게 JS엔진은 각 런타임 context에서 서로를 연결할까?
브라우저-실행 적용 관점에서.
1.ESM. 필요한 것들을 import하여 참조한다.
2.빌드 단계의 bundler. 브라우저나 엔진에 전달되기 전에 연결된다.
3.global scope
var moduleOne = (function one(){
// ..
})();
var moduleTwo = (function two(){
// ..
function callModuleOne() {
moduleOne.someMethod();
}
// ..
})();
위가 별도의 파일로 로드되는 것과 똑같.
global scope 기능.
JS exposes its built-ins:
primitives: undefined, null, Infinity, NaN
natives: Date(), Object(), String(), etc.
global functions: eval(), parseInt(), etc.
namespaces: Math, Atomics, JSON
friends of JS: Intl, WebAssembly
The environment hosting the JS engine exposes its own built-ins:
console (and its methods)
the DOM (window, document, etc)
timers (setTimeout(..), etc)
web platform APIs: navigator, history, geolocation, WebRTC, etc.
Node에서 실제로 global scope에 속하지 않는 것들.require(), __dirname, module, URL, and so on.
환경마다 다름.
<script>
(tag, in markup,DOM 등)에 의해 웹 페이지에 로드되면 글로벌 스코프에 식별자들이 선언된다.
var studentName = "Kyle";
function hello() {
console.log(`Hello, ${ studentName }!`);
// console.log(`Hello, ${ window.studentName }!`);
}
hello();
// Hello, Kyle!
window.hello();
// Hello, Kyle!
전역 변수가 글로벌 객체의 속성을 쉐도우 할 수도. 전역은 var 써라.
window.something = 42;
let something = "Kyle";
console.log(something);
// Kyle
console.log(window.something);
// 42
쓰지마. id 속성을 가지는 DOM element는 자동으로 그를 참조하는 전역 변수를 만든다.
<ul id="my-todo-list">
<li id="first">Write a book</li>
..
</ul>
first;
// <li id="first">..</li>
window["my-todo-list"];
// <ul id="my-todo-list">..</ul>
브라우저 기반 JS에서 이상한게 있다.
var name = 42;
console.log(name, typeof name);
// "42" string
window.name은 브라우저 컨텍스트에 이미 정의된 글로벌. 글로벌 객체의 속성으로.. let으로 쉐도잉 가능!
JS 프로그램과 별개의 thread로 JS 파일을 실행 가능하게 해주는 대신 제한 사항이 많다.
self
를 사용하여 전역에 접근 가능.
var studentName = "Kyle";
let studentID = 42;
function hello() {
console.log(`Hello, ${ self.studentName }!`);
}
self.hello();
// Hello, Kyle!
self.studentID;
// undefined
도구에 불과. 다음과 같은 부분에서 차이가 발생할 수 있다.
최상위 스코프에서 써도 전역이 아니다.
노드는 각 싱글 로드된 파일들을 취급. 파일의 최상위도 글로벌이 아니고 모듈 함수 내부라고 생각하면 된다. require를 통해서도 많은 전역을 정의하지만 실제로는 아니다. 전역 변수를 정의하고 싶다면 global
. 즉, JS에 정의된 것이 아니라 Node에 의해.
ES2020, 전역 스코프 객체에 대한 표준화된 참조로 globalThis
가 정의됐다.
pre-globalThis 폴리필
const theGlobalScopeObject =
(typeof globalThis != "undefined") ? globalThis :
(typeof global != "undefined") ? global :
(typeof window != "undefined") ? window :
(typeof self != "undefined") ? self :
(new Function("return this"))();