这几天学习了一下javascript作用域链,感到这个挺重要的,所以写一篇文章分享一下:
1. 作用域链:
当代码在一个环境中执行时,会创建由变量对象构成的一个作用域链。作用域链的用途是:保证对执行环境有权访问的搜友变量和函数的有序访问。
2. 在作用域链中查找标识符:
当在某环境中为了读取或写入而引用一个标识符时,必须通过搜索来确定该标识符实际代表什么。搜索过程从作用域链的前端开始,向上逐级查询与给定名字匹配的标识符。如果在局部环境中找到该标识符,搜索过程停止,变量就绪。如果在局部环境中没有找到该变量名,则继续沿作用域链向上搜索。搜索过程将一直追溯到全局环境的变量对象。如果在全局环境中也没有找到这个标识符,则意味着这个标识符为声明。
3. 现在就来看看例子吧。。。
3.1 var
name =
"hello"
;
function
test(){
alert(name);
//undefined
var
name =
"world"
;
alert(name);
//world
}
test();
alert(name);
//undefined
这一句话的时候,js引擎会在自身的对象作用域中找到name属性,并且输出他的值(undefined),当执行到
var
name =
"world"
;
时name属性的值已经被赋值为world了因此下一条alert就打印出world了!
3.2 var
name =
"hello"
;
function
test(){
alert(name);
//hello
name =
"world"
;
alert(name);
//world
}
test();
name =
"world"
;
因此当第一条
alert(name);
//hello
时候会在全局环境变量中查找到hello的值,当执行了
name =
"world"
;
全局变量中的name就被赋值为world了,因此在进行
alert(name);
//world
的时候就是world了。
3.3 name =
"hello"
;
function
test(){
alert(name);
//undefined ---》》》在自己的作用域中查找到的
var
name =
"world"
;
alert(name);
//world
}
test();
name =
"hello"
;
function
test(){
alert(name);
//hello
name =
"world"
;
alert(name);
//world
}
test();
补充::奥 对了,还有一点要补充一下:
在web浏览器中,全局执行环境被认为是Window对象,因此所有的全局变量和函数都是作为Window对象的属性和方法创建的,某个执行环境中的所有代码执行完毕后该环境被销毁,保存在其中的所有变量和函数定义也随之销毁。全局执行环境知道应用程序退出-----例如关闭浏览器或者网页时才会销毁!!!