JavaScript Lexical Scope
来源:互联网 发布:mac mp4 srt 编辑:程序博客网 时间:2024/06/07 01:08
I understand them through examples :)
First, Lexical Scope (also called Static Scope), in C-like syntax:
void fun(){ int x = 5; void fun2() { printf("%d", x); }}
Every inner level can access its outer levels.
There is another way, called Dynamic Scope used by first implementation of Lisp, again in C-like Syntax:
void fun(){ printf("%d", x);}void dummy1(){ int x = 5; fun();}void dummy2(){ int x = 10; fun();}
Here fun
can either access x
in dummy1
or dummy2
, or any x
in any function that call fun
with x
declared in it.
dummy1();
will print 5
dummy2();
will print 10
The first one is called static because it can be deduced at compile-time, the second is called dynamic because the outer scope is dynamic and depends on the chain call of the functions.
I find static scoping easier for the eye. Most languages went this way eventually even Lisp (can do both, right?). Dynamic scoping is like passing references of all variables to the called function.
An example of why the compiler can not deduce the outer dynamic scope of a function, consider our last example, if we write something like this:
if(/* some condition */) dummy1();else dummy2();
The call chain depends on a run time condition. If it is true, then the call chain looks like:
dummy1 --> fun()
If the condition is false:
dummy2 --> fun()
The outer scope of fun in both cases is the caller plus the caller of the caller and so on.
Just to mention that C language does not allow nested functions nor dynamic scoping.
- JavaScript Lexical Scope
- Lexical scope and function closures in R
- [你所不知的JavaScript] 作用域和闭包 Chapter2 Lexical Scope (词法作用域)
- Scala-2 - 6 - Lecture 1.6 - Blocks and Lexical Scope (8_00)
- JavaScript的scope原理
- javascript 的 scope
- JavaScript作用域(Scope)
- Scope in JavaScript
- JavaScript 作用域 (Scope)
- Javascript 变量 scope
- javascript scope chain
- javascript scope chain
- javascript scope 精华
- JavaScript中scope介绍
- [Javascript] variable, scope, scope chain, execution context
- [ javascript ] javascript中的[[scope]],scope chain,execution context!
- JavaScript has no block scope
- javascript作用域scope例子
- 【LeetCode】Linked List Cycle I&II
- android回调函数
- ubuntu10.10,安装flash插件
- 【代码片段】两列布局
- 加性高斯白噪声信道(AWGN)下的digital调制格式识别分类
- JavaScript Lexical Scope
- 转存
- POJ-1005
- 四种方案解决ScrollView嵌套ListView问题
- 王家林亲授《DT大数据梦工厂》大数据实战视频“Scala深入浅出实战经典”47
- 【数据结构之树状数组】
- 线性表的顺序存储设计和实现 - API函数实现
- 作用域链(Scope Chain)
- delphi 遍历所有文件夹