Posts This/闭包
Post
Cancel

This/闭包

  1. 全局执行上下文中,指向全局对象(window)
  2. 函数执行上下文中,指向调用函数的对象或window或undefined
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
var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f();
}
checkscope();
[global_scope] => [check_global , global_scope] =>  [f_scope, check_global, global_scope] =>  [check_global , global_scope] =>  [global_scope]

var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f;
}
checkscope()();
[global_scope] => [check_global , global_scope] => [f_scope, global_scope] => [global_scope]

Summary:
    1.在函数执行栈中执行f()
    2.在上下文执行栈中执行f()

闭包

  • 闭包调用时包含函数创建时作用域中的所有变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1: function createCounter() {
 2:   let counter = 0
 3:   const myFunction = function() {
 4:     counter = counter + 1
 5:     return counter
 6:   }
 7:   return myFunction
 8: }
 9: const increment = createCounter()
10: const c1 = increment()
11: const c2 = increment()
12: const c3 = increment()
13: console.log('example increment', c1, c2, c3)

// 1 2 3

createCounter函数压入全局上下文中
声明变量increment, 全局搜索createCounter, 找到后切换为函数上下文,返回带有变量的闭包
声明变量c1,调用increment, couter初始值为0, 赋值为1,
声明变量c1,调用increment, couter初始值为1, 赋值为2,
声明变量c1,调用increment, couter初始值为2, 赋值为3,

非闭包

1
2
3
4
5
6
7
8
9
10
11
12
13
1: let a = 3
2: function addTwo(x) {
3:   let ret = x + 2
4:   return ret
5: }
6: let b = addTwo(a)
7: console.log(b)

 声明变量a赋值3,在执行上下文中,存下addTwo
 声明变量b, 在上下文中搜索addTwo函数,创建新的执行上下文,传入参数 a=3,执行
 声明变量ret,x赋值3, 返回5
 addTwo执行上下文被销毁, 变量x和 ret被销毁,返回全局执行上下文中
 输出5
This post is licensed under CC BY 4.0 by the author.