作用域链、闭包及其它

1:作用域链:

当函数被创建时,就存在了作用域及执行环境。而作用域链是当函数被执行时存在的。
当代码在一个环境中执行时,会创建变量对象的一个作用域链。其用途是保证对执行环境有权访问的所有变量和函数的有序访问(高级教程)。作用域链的前端始终是当前被执行的函数。下一个是包含当前函数的函数活着直接时window全局环境。

外部访问不到内部声明的变量。而内部可以访问到外部声明的变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var color = "blue";

function changeColor() {
var anotherColor = "red";

function swapColor() {
var tempColor = anotherColor;
anotherColor = color;
color = tempColor;

//可以访问 color,anotherColor,tempColor;
}

swapColor(); //可以访问 color,anotherColor;
}
changeColor() //只能访问 color;

而通过闭包可以实现外部访问内部声明的变量。而且变量不被垃圾回收机制回收。

2:闭包

简单来讲就是函数中套函数

高级教程定义:闭包是有权访问 另一个函数作用域中的变量的 函数;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

function fn() {
var n = 0;
return function () {
return n++;
}
}
var n = fn();
n(); //0
n(); //1
n(); //2

//另一个
var color = "blue";

var obj = {
color:"red",

getColor:function () {
return function () {
return this.color;
}
}
}

alert(obj.getColor()()); //闭包

3:this及call,apply,bind

this指的是调用函数的那个对象;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var color = "blue";

var obj = {
color:"red",

getColor:{
color:"purple",
sonColor:function () {
return this.color;
}
}
}

// alert(obj.getColor.sonColor()); //purple

var n = obj.getColor.sonColor;
alert(n()); //blue;

用call,apply,bind可以改变函数体内this的指向

1
2
3
4
5
6
7
8
9
10
11
12
13

// call 和 apply:在特定的作用域中调用函数,等于设置函数体内this的值。
window.color = 'red';
var o = {color: 'blue'};

function sayColor() {
console.log("color",this.color);
}
// sayColor.call(o); //直接打印出来了

//而bind需要再调用一次
var obj = sayColor.bind(o);
obj();

bind()将函数绑定到指定环境的函数,带一个函数和一个环境
实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function bind(fn, context) {
return function () {
return fn.apply(context, arguments);
}
}

var handler = {
mes:"Event handler",

handleClick:function () {
alert(this.mes);
}
}

// type.addEventListener('click',bind(handler.handleClick, handler),false);

// es6中自带的bind函数
// type.addEventListener('click',handler.handleClick.bind(handler),false);

文章目录
  1. 1. 1:作用域链:
  2. 2. 2:闭包
  3. 3. 3:this及call,apply,bind
,