Part 06 · Runtime · 6.1.01

ECMAScript engine, realm, agent và host

Spec định nghĩa language semantics; browser/Node cung cấp event loop, timers, DOM, network và process APIs. Tách hai lớp này giúp giải thích đúng khi code chạy khác host.

Model: execution context mô tả evaluation state; call stack chỉ là hình dung các context đang active, không phải toàn bộ memory model hay scheduler.

1. Execution contexts và environments

Script/module evaluation tạo execution contexts với lexical environment, variable environment, private environment và realm. Binding lookup đi qua environment chain; function call tạo context mới rồi return context cũ. Hoisting, TDZ và strict mode là semantics của binding initialization, không phải “code được chạy trước” một cách đơn giản.

global context -> call f() -> call g()
                    active execution contexts (conceptual stack)

2. Realm và object identity

Mỗi realm có intrinsics riêng (Object, Array, Error, prototypes). Object từ iframe/worker khác có constructor identity khác nên value instanceof Array có thể bất ngờ. Khi qua realm, ưu tiên semantic checks như Array.isArray, branded APIs hoặc schema validation thay vì so constructor.

3. Agent, jobs và shared memory

Agent thực thi ECMAScript jobs theo thứ tự; Promise reactions là jobs được host schedule. “JavaScript single-threaded” chỉ mô tả một execution agent tại thời điểm, không phủ worker agents, Web Workers, Node worker threads hoặc shared memory. SharedArrayBuffer/Atomics mới tạo coordination memory-level và cần invariant tránh data race/livelock.

4. Strict mode, modules và host loading

ES modules luôn strict, có scope riêng, static dependency graph và live bindings; top-level await có thể làm chậm evaluation của graph phụ thuộc. Host quyết định module resolution, fetch, caching và permissions, nên cùng source có behavior khác giữa browser, Node và bundler.

Interview answer: “I separate ECMAScript semantics from host scheduling and APIs. I use realms/agents/jobs to explain identity and ordering, then verify host-specific behavior with a minimal reproduction.”
Tài liệu: ECMAScript Specification · MDN Execution Model · MDN Atomics