YvetteLau / Step-By-Step

不积跬步,无以至千里;
704 stars 66 forks source link

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

Open YvetteLau opened 5 years ago

YvetteLau commented 5 years ago
var a = 5;
function todo() {
    var a = 9;
    return function() {
        a = 7;
    }
}
todo()();
console.log(a);
teacc commented 5 years ago

5

ZadaWu commented 5 years ago

5

clark-maybe commented 5 years ago

5

jinsong5 commented 5 years ago

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

RalapChen commented 5 years ago

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

shenshuangdao commented 5 years ago

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

cute1baby commented 5 years ago

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

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