If we think of local variables as properties of some kind of implementation-defined object, then there is another way to think about variable scope.还有一句: JavaScript is a lexically scoped language. 通过英汉词典查出来的意见直接套上去真的不知所云,是不是应该找双解的词典才能理解当中的含义?
希望得到指教,谢谢!
请教你怎么理解“词法范围的语言”?受你的启示,我认为应该译成这样:“如果我们认为局部变量是某种实例化对象的属性,这样的话,我们就可以用另外的角度去看待变量的作用域了。”
function test(){
var var2 = 1;
function inner(){
var var3 = 2;
function inner_of_inner() {
alert(var1);
alert(var2);
alert(var3);
} inner_of_inner();
}
inner();
}
每个函数内部都保留了上一层函数的scope的引用,以便能查找到上一层定义的变量。在本例中,inner_of_inner函数中使用了变量var1,这个查找过程是:inner_of_inner内部有inner函数的scope引用,于是在inner的scope上查找var1,结果没找到,inner的scope上又保留了test函数的scope的引用,于是继续在test的scope上查找var1,继续查找,直到查找到golbal scope,这时找到了var1。
如果某个变量,查找到golbal scope仍然没有发现引用,那么就会得到undefine。
scope chain和prototype chain的概念完全相同,都是追溯查找的方式实现的。
没有词法作用域的语言,在函数中不会保存上一层作用域的scope引用的。例如C语言,只有global和local两个作用域,不存在scope chain的说法。
希望我的理解能够帮到你。