关于Javascript作用域链的八点总结_javascript技巧

WBOY
Release: 2016-05-16 17:10:24
Original
1474 people have browsed it

1. JavaScript函数的作用域链分为定义时作用域链和运行时作用域链;

2.函数被定义的时候,它有一个属性[[scope]]标明它的定义作用域链,定义时作用域链[[scope]]遵守这样的规则:一个函数的定义时作用域链[[scope]]总是它所在的外部函数的执行时作用域链;

3.全局函数的定义作用域链只包含window的属性;

4.一个函数的执行时作用域链总是在定义时作用域链的头部压入当前活动对象(它包含this,arguments,参数,局部变量);

5.函数执行时,变量寻址总是从作用域链的顶端朝下寻找;所以全局变量的寻址速度最慢;

6.内部函数被执行的时候,他仍然能够访问它完整的作用域链。这就是闭包能够在运行时能够访问已经结束的外部函数定义的变量的原因;

7.函数执行遇到with语句时,会临时在作用域链顶部压入with指定的对象的所有属性作为作用域链最顶端;

8.函数执行遇到catch的时候,会临时在作用域链顶部压入catch指定的错误对象作为作用域链的最顶端;

下面给一个例子并绘制出作用域链,以加深理解:

有这么一段代码:

复制代码代码如下:

function assignEvents(){
var id = "xdi9592";
document.getElementById("save-btn").onclick = function(event){
saveDocument(id);
};
}

把此函数产生的匿名闭包称为Closure,则绘制出下图为assignEvent执行时作用域链和Closure的定义时作用域链:

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!