简体   繁体   English

理解 JavaScript 中的闭包作用域

[英]Understanding closure scope in JavaScript

I've been reading the "You Don't Know JS" book series and I have a question regarding closures .我一直在阅读“你不懂 JS”系列丛书,我有一个关于闭包的问题。

 var a; function wait() { a = 10; return setTimeout(function timer() { console.log('Hello closure ', a); }, 1000) } const fn = wait; fn(); console.log(a);

If I asked for the value of a in the console without executing the function (fn()), it will say it is undefined which is correct.如果我在没有执行函数 (fn()) 的情况下在控制台中询问a的值,它会说它是未定义的,这是正确的。

Now if I execute the function fn() after 1 second it will print Hello Closure 10 I know that timer has a closure over wait function, that's why it prints that value, even when it is executed outside the lexical scope where it was defined.现在,如果我在 1 秒后执行函数fn()它将打印Hello Closure 10我知道计时器在等待函数上有一个闭包,这就是它打印该值的原因,即使它是在定义它的词法范围之外执行的。

But if a print a value in the console now ( after running fn() ) it output also 10 , so I guess this is not lexical scope , from global scope the lookup never goes down (I mean it looks deep down in the nested functions), it always look for the variables up (going up to the enclosing scopes of functions).但是如果现在在控制台中打印一个值(在运行 fn() 之后)它也会输出10 ,所以我想这不是词法范围,从全局范围开始查找永远不会下降(我的意思是它在嵌套函数中看起来很深) ),它总是向上查找变量(向上到函数的封闭范围)。

So I wonder if this is closure too or the variable just got another value after running the function and that's all?所以我想知道这是否也是闭包,还是在运行函数后变量只是获得了另一个值,仅此而已?

If you instantiate the variable inside the function, it will prevent global variables of the same name from changing.如果在函数内部实例化该变量,将阻止同名的全局变量发生变化。 I added a var a = 10 into the function.我在函数中添加了一个var a = 10 I left the globally scoped var there so you can see that now it doesn't change.我把全局范围的变量留在那里,所以你可以看到它现在没有改变。 This is more of a variable scoping issue.这更像是一个可变范围的问题。

The closure was working as you expected, just you were setting a global variable.闭包按您的预期工作,只是您设置了一个全局变量。

 var a; function wait() { var a = 10; return setTimeout(function timer() { console.log('Hello closure ', a); }, 1000) } const fn = wait; fn(); console.log(a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM