JavaScript works behind the scenes -- Engine and Runtime
what is a JavaScript engine?
program that executes JavaScript code. JavaScript引擎是运行JavaScript代码的程序。
how engine works?
JavaScript contains a call stack and a heap. (调用栈和堆)
the call stack is where our code is actually executed using something called execution contexts.
the heap is an unstructured memory pool which store all the objects that our application needs.
how the code is compiled to machine code?(编译)
汇编语言:翻译成机器码然后执行
解释型语言:获取源代码和执行程序是同时进行的,但是相对于汇编语言,解释型语言编译非常慢
即时编译:这里没有可移植文件,源代码被编译成机器码之后立即执行(JavaScript是即时编译)
how the code is executed in engine? (运行)
-
解析:源代码会变成AST,abstract tree,抽象语法树
during the parsing process, the code is parsed into a data structure called the abstract tree. This works by first splitting up each line of code into pieces that are meaningful the language like the const or function keywords, and then saving all these pieces into the tree in a structured way. This step also checks if there are any syntax errors(语法错误) and the resulting tree will later be used to generate the machine code.
-
将ast编译成机器码
-
机器码将被立即执行(这一步发生在call stack中)
-
在程序运行的过程中,同时进行着一个优化的步骤,在已经运行的程序执行期间重新编译。优化之后,未被优化的代码被简单扫过,对于已优化的代码重新执行。
这些步骤都是在引擎的特殊线程中执行,不会在主线程中执行
runtime(运行机制)
web api:这些api都不属于JavaScript的范围,如果没有浏览器提供这些api机制,JavaScript也没有办法去控制比如说DOM。
callback query:在addEventListener这个函数里面,第一个参数我们定义的是监听的事件,比如说‘click’,我们监听的就是点击事件。第二个参数是回调函数,如监听到点击事件之后执行的函数,这个函数执行的机制是什么?当监听到点击事件的时候,我们会将回调函数放入callback query中等待执行,当call stack中没有方法的时候,callback query中的方法就会进去call stack中执行(事件循环)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报