-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
1 changed file
with
98 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
|
||
#JavaScript之解释与执行机制 | ||
|
||
不同于其他的编译性语言如Java、C等,运行前需要将其编译为机器语言的文件,JavaScript在运行程序的时候才翻译,即JavaScript是一门解释性脚本语言. | ||
|
||
> 解释型语言:程序不需要编译,程序在运行时才**翻译**成机器语言,每执行一次都要翻译一次。 | ||
> 编译型语言:程序在执行之前需要一个专门的**编译**过程,把程序编译成 为机器语言的文件,运行时不需要重新翻译,直接使用编译的结果。 | ||
*JavaScript翻译过程又做解释过程。* | ||
|
||
##JavaScript解释与执行 | ||
|
||
JavaScript按照代码块来进行解释和执行,代码块间相互独立,但变量和方法共享。 | ||
|
||
> JavaScript中的代码块是指由`<script></script>`标签分割的代码段。 | ||
###解释 | ||
|
||
JavaScript代码块在执行时先由解释器进行解释,主要过程是声明所有var变量(并未初始化赋值,当前值为undefined)、解析**声明式**函数语句,而且是先预定义变量再预定义函数。 | ||
|
||
|
||
> JavaScript中函数定义主要主要有两种:声明式与函数表达式。 | ||
``` | ||
//声明式函数 | ||
function test() { | ||
//... | ||
} | ||
//函数表达式 | ||
var test = function() { | ||
//... | ||
} | ||
``` | ||
|
||
###代码分析 | ||
|
||
1. **试分析以下代码:** | ||
|
||
``` | ||
alert(a); | ||
alert('ok'); | ||
var a = 1; | ||
``` | ||
弹出undefined和ok。因为执行时先解释:1.定义var变量,并未初始化赋值,当前值为undefined。 | ||
|
||
2. **请君细看** | ||
|
||
``` | ||
alert(a); | ||
alert('ok'); | ||
a = 1; | ||
``` | ||
会发现报错了,因为a未定义,解释时定义var变量,并不会定义此处的a。 | ||
|
||
到这里我们又发现了一个值得关注的问题--定义变量的方式。 | ||
> JavaScript变量分两种:全局变量和局部变量。像a = 1;这种定义默认是创建全局变量,其实就相当于window.a = 1;而var a = 1;这种格式是定义一个当前作用域下的变量。解释时只会定义var格式的变量。 | ||
3.**函数相关** | ||
|
||
``` | ||
<script> | ||
a(); | ||
var a = function(){ //声明式函数 | ||
alert("函数表达式"); | ||
} | ||
alert('ok1'); | ||
</script> | ||
<script> | ||
a(); | ||
function a(){ //声明式函数 | ||
alert("声明式函数"); | ||
} | ||
alert('ok2'); | ||
</script> | ||
``` | ||
结果如何呢?运行上述代码你会发现弹出了“声明式函数”和“ok2”。 | ||
为什么呢,这里就涉及到前面所说的**代码块之间是相互独立的**,故前面的a()虽然报错了,阻塞了ok1弹出;但是第二段script代码并不受影响。 | ||
|
||
第一段代码缘何报错?因为代码执行时先解释声明式函数而不会解释函数表达式,此时只是定义了a变量,未初始化,其值为undefined,不是函数。 | ||
|
||
总结:到此时对JavaScript的解释与执行机制、顺序也算有初步的认识了。 | ||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|