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中执行(事件循环)