Thanks to visit codestin.com
Credit goes to github.com

Skip to content

执行上下文中的2道题 #17

@Clearives

Description

@Clearives

第1题

var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f;
}
checkscope()();

这端代码输出的答案是:local scope;为什么呢?
执行过程伪代码:

- [全局]EC
 - [local scope]EC
  - [f]EC
f函数执行能访问到local scope,所以输出local scope

第2题

var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f;
}
checkscope()();

这端代码输出的答案是:local scope;为什么呢?
执行过程伪代码:

- [全局]EC
 - [local scope]EC
  - 闭包
执行到闭包时,[local scope]EC已出栈,所以闭包内this指向window,但是我们知道闭包能访问上层变量,也就是[local scope]EC里的变量,所以打印出来的也是local scope

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions