Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

以下代码的输出的结果为: #45

Open
YvetteLau opened this issue Jul 16, 2019 · 7 comments
Open

以下代码的输出的结果为: #45

YvetteLau opened this issue Jul 16, 2019 · 7 comments

Comments

@YvetteLau
Copy link
Owner

var a = 5;
function todo() {
    var a = 9;
    return function() {
        a = 7;
    }
}
todo()();
console.log(a);
@teacc
Copy link

teacc commented Jul 16, 2019

5

2 similar comments
@ZadaWu
Copy link

ZadaWu commented Jul 16, 2019

5

@clark-maybe
Copy link

5

@jinsong5
Copy link

5
变量引用会沿着作用域链去查找,todo()()之后改变的是todo作用域内部的a的值,由9变成7,console时候输出的是window下的a,所以还是5

@RalapChen
Copy link

5,因为a=9是在闭包,console是window

@shenshuangdao
Copy link

5,闭包执行后内部的a从9变成了7,最外层的变量a不变

@cute1baby
Copy link

cute1baby commented Jul 16, 2019

对上面的函数改造了一下:
还是考察作用域的知识点,分清全局作用域、局部作用于和闭包。

var a = 5;
function todo() {
    var a = 9;
    console.log("外层a:"+a);
    return function() {
        a = 7;
        console.log("闭包a:"+a);
    }
}
todo()();
console.log("全局a:"+a);

输出:外层a:9 闭包a:7 全局a:5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants