This article analyzes the usage of JavaScript scope chain (Scope Chain) with examples. Share it with everyone for your reference, the details are as follows:
I have heard about the scope chain of js for a long time, and have read several introductory blog posts, but my understanding has always been ambiguous. Recently, I carefully read the book "Understanding Javascript" and felt that it was written very profoundly. In the "Space and Time of Code" section, there is a section that introduces the scope chain with only a few words, which left me with endless aftertaste (actually I still understand it). Ambiguous^_^). Now organize your reading notes, draw on online resources, and write them down.
1. Let’s start with a simple question
What results will be displayed when the following js code is run on the page:
var arg = 1; function fucTest(arg) { alert(arg); var arg = 2; //alert(arg); } fucTest(10);
What’s your answer? That's right, 10 pops up. My understanding is this, the funTest function has a formal parameter arg, the funTest function passes in the actual parameter 10, and the alert method just pops out 10, embarrassing.
Okay, here comes the question again:
var arg = 1; function funcTest() { alert(arg); var arg = 2; } arg = 10; funcTest();
What’s the answer? If it were me 5 years ago, I would definitely not think about it any further, it would still be 10! Why should you think about such a simple question? My understanding is this: the funTest function is a parameterless function. Inside the function, the external (global) variable arg is called through the alert method. Before the function is executed, arg is assigned a value of 10. After the arg value is popped out, the arg value is changed to 2. , so the popup value is 10.
Is it really 10? Yes or no?
Test result: "undefined" pops up, waterfall sweat.
2. Understand the scope chain, starting from the JavaScript operating mechanism
1. The running sequence of js
If a document flow contains multiple script code segments (js code separated by script tags or introduced js files), their running order is:
Step 1. Read the first code segment (the js execution engine does not execute the program line by line, but analyzes and executes it piece by piece)
Step 2. Perform syntax analysis. If there are any errors, a syntax error will be reported (such as mismatched brackets, etc.) and jump to step 5
Step 3. Do "pre-parsing" of var variable and function definitions (no errors will ever be reported, because only correct declarations are parsed)
Step 4. Execute the code segment and report an error if there is an error (for example, the variable is undefined)
Step 5. If there is another code segment, read the next code segment and repeat step 2
Step 6. End
The above analysis is clear enough. The red fonts in steps 2, 3 and 4 may be a blind spot for us novices to understand, especially the "pre-parsing" in step 3. If you don't know what pre-parsing is, always I feel uneasy. The fourth step of "report an error if there is an error" is also often encountered. For example:
function funcTest() { alert(arg); var arg = 2; } funcTest();
上面这段代码执行时,弹出“undefined”,也就是说arg没有定义,js的变量不是不用定义也可以吗?
2、语法分析和“预解析”
(1)、从解释型语言的编译过程说起
众所周知,javascript是解释型语言,它不同于c#和java等编译型语言。对于传统编译型语言来说,编译步骤分为:词法分析、语法分析、语义检查、代码优化和字节生成;但对于解释型语言来说,通过词法分析和语法分析得到语法树后,就可以开始解释执行了。
a、词法分析
简单地说,词法分析是将字符流(char stream)转换为记号流(token stream)。
但是这个转换过程并不是可以用一句话就可以概括的那么简单,我们可以试着用伪代码理解一段简单的程序:
代码var result=x-y;的转换大致可以表示如下:
NAME "result"
EQUALS
NAME "x"
MINUS
NAME "y"
SEMICOLON
b、语法分析
简单地说,语法分析就是为了构造合法的语法分析树,而语法分析树可以直观地表示出推导的过程。
那么什么是语法分析树?简单地说,就是程序推导过程的描述。但是到底什么是语法树,请参考专业文章,本篇略过。
c、其他
通过语法分析,构造出语法分析树后,接下来还可能需要进一步的语义检查。对于传统强类型语言来说,语义检查的主要部分是类型检查,比如函数的实参和形参类型是否匹配等等。
结论:通过上面的分析可以看出,对于javascript引擎来说,肯定有词法分析和语法分析,之后可能还有语义检查、代码优化等步骤,等这些编译步骤完成之后(任何语言都有编译过程,只是解释型语言没有编译成二进制代码),才会开始执行代码。
(2)、执行过程
a、javascript的作用域机制
通过编译,javascript代码已经翻译成了语法树,然后会立刻按照语法树执行。
进一步的执行过程,需要理解javascript的作用域机制:词法作用域(lexcical scope)。通俗地讲,就是javascript变量的作用域是在定义时决定而不是执行时决定,也就是说词法作用域取决于源码,编译器通过静态分析就能确定,因此词法作用域也叫做静态作用域(static scope)。但需要注意,with和eval的语义无法仅通过静态技术实现,所以只能说javascript的作用域机制非常接近词法作用域(lexical scope).
javascript引擎在执行每个函数实例时,都会创建一个执行环境(execution context)。执行环境中包含一个调用对象(call object), 调用对象是一个scriptObject结构(scriptObject是与函数相关的一套静态系统,与函数实例的生命周期保持一致),用来保存内部变量表varDecls、内嵌函数表funDecls、父级引用列表upvalue等语法分析结构(注意varDecls和funDecls等信息是在语法分析阶段就已经得到,并保存在语法树中。函数实例执行时,会将这些信息从语法树复制到scriptObject上)。
b、javascript作用域机制的实现方法
词法作用域(lexical scope)是javascript的作用域机制,还需要理解它的实现方法,就是作用域链(scope chain)。作用域链是一个name lookup机制,首先在当前执行环境的scriptObject中寻找,没找到,则顺着upvalue到父scriptObject中寻找,一直lookup到全局调用对象(global object)。
现在回过头来分析第二个问题:
var arg = 1; function funcTest() { alert(arg); var arg = 2; } arg = 10; funcTest();
在执行funcTest函数时,也即进入了funcTest对应的作用域,js引擎在执行时,当遇到对变量名或者函数名的使用时,会首先在当前作用域(也即funcTest对应的作用域)查找变量或者函数(显然,arg变量在funcTest对应的作用域里被定义为var arg=2 所以alert方法的参数采用的是当前作用域的arg,但是因为arg被定义在alert方法后,所以arg变量默认值为undefined)。当然,如果没有找到就到上层作用域查找,依此类推(作用域范围可以持续到javascript运行环境的根:window对象)。
最后,让你看的更清楚,上面的代码其实可以等价于:
var arg = 1; function funcTest() { var arg; //默认值undefined alert(arg); arg = 2; } arg = 10; funcTest();
c, closure
When a function instance is executed, a closure is created or associated with it. (About closures, I plan to write another study note)
scriptObject is used to statically save variable tables related to functions, and closures dynamically save these variable tables and their running values during execution;
The life cycle of a closure may be longer than that of a function instance. The function instance will be automatically destroyed after the active reference is empty;
The closure will be recycled by the JavaScript engine after the data reference is empty (in some cases, it will not be recycled automatically, resulting in a memory leak).
ps: This section about "execution process" is a bit difficult to pronounce. There are many nouns, but don't be intimidated by them. Once you understand the execution context, call object, lexical scope, Concepts such as scope chain and closure can easily solve many phenomena in JavaScript.
3. Conclusion
Through the analysis of the second paragraph, compare it with the judgment made by the author in the first paragraph (Do you also think that the author’s previous analysis and conclusions are naive (even if the results happen to be right sometimes!)?! It’s not superficial. , ^_^), you will find that there are so many "mysteries" in JavaScript, but it is not easy to truly understand and master it? Let’s “understand” it first and then talk about it.
I hope this article will be helpful to everyone in JavaScript programming.