什么是 JavaScript 引擎
What is the JavaScript engine
一句话:引擎是把 JS 源码变成机器能执行的东西的那个程序。Chrome / Node 用 V8,Firefox 用 SpiderMonkey, Safari 用 JavaScriptCore。
大致流程:源码 → 解析成 AST → 生成字节码 →解释器先跑起来, 同时监控哪段代码被反复执行(热点), 把热点交给 JIT 编译器编译成机器码。 这套「先解释、后即时编译」的做法让 JS 既能马上启动、 又能在热点上接近原生速度。
会追问:「引擎和运行时(runtime)什么区别?」 —— 这是真考点。引擎只管执行 JS 语言本身, 它不认识 setTimeout、fetch、document、fs—— 这些都是宿主环境(浏览器 / Node)提供的 API。
所以「事件循环属于引擎吗?」答案是不属于, 它是运行时的一部分(见 #305)。这个区分答对了很加分。
还会追问内存:引擎管两块 ——调用栈(执行上下文、原始值)和堆(对象、数组、函数)。 这正好对应下一题。
In one line: the engine is the program that turns JS source into something the machine can run. Chrome and Node use V8, Firefox uses SpiderMonkey, Safari uses JavaScriptCore.
Roughly the pipeline: source → parse into an AST → emit bytecode → the interpreter starts running it while watching which parts run over and over (the hot paths), and hands those to the JIT compiler to be turned into machine code. Interpret first, compile later — that is what lets JS start instantly and still hit near-native speed where it counts.
Follow-up: “What is the difference between the engine and the runtime?” — this is the real question. The engine only executes the language itself. It knows nothing about setTimeout, fetch, document or fs — those are APIs the host environment (browser or Node) hands you.
So “is the event loop part of the engine?” — no, it belongs to the runtime (see #305). Getting this distinction right earns real credit.
Another follow-up, on memory: the engine manages two areas — the call stack (execution contexts, primitive values) and the heap (objects, arrays, functions). Which lines up exactly with the next question.