Javascript 闭包/变量范围问题 - 我知道它有效,但为什么?
我使用 JS 进行开发已经有一段时间了,虽然我知道下面的代码可以工作,但我不太明白为什么它可以工作。
在我看来,我在 testClosure 函数中定义了 testString,并且我期望该变量在 testClosure 函数完成时“消失”,因为它是局部变量。
但是,当我使用计时器调用内部函数时,它仍然知道 testString 变量。为什么?当 testClosure 执行完毕时,这个变量不是在五秒前就消失了吗?内部函数是否获取对 testClosure 中所有变量的引用,并且它们在所有内部函数完成之前保持有效?
function testClosure() {
var testString = 'hai';
// after 5 seconds, call function below
window.setTimeout(function() {
// check if function knows about testString
alert(testString);
}, 5000);
}
testClosure();
I've been developing with JS for a while, and while I know that code below works, I don't really understand why it works.
The way I see it, I've defined testString in testClosure function, and I'm expecting that variable to 'go away' when testClosure function is done, since it's local variable.
However, when I call inner function with a timer, it's still aware of testString variable. Why? Isn't that variable gone five seconds ago when testClosure finished executing? Does the inner function get reference to all variables within testClosure, and they stay valid until all inner functions are done?
function testClosure() {
var testString = 'hai';
// after 5 seconds, call function below
window.setTimeout(function() {
// check if function knows about testString
alert(testString);
}, 5000);
}
testClosure();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
function
特殊形式创建词法作用域。在该范围内创建的任何对象都将在其创建时在范围内按词法查看环境(名称到值的绑定)。事实上,创建函数是在 JavaScript 中创建词法作用域的唯一方式,这就是为什么你总是看到这样的扭曲:
The
function
special form creates lexical scope. Any object created within that scope will see the environment (the binding of names to values) lexically in scope at the time of its creation.Indeed, creating a function is the only way to create lexical scope in JavaScript, which is why you see contortions like this all the time:
总之,是的。现货。
In a word, yes. Spot on.
testString 存在于 testClosure 的范围内,因此就计时器而言,testString 是一个全局变量。
JavaScript 闭包如何工作?
有更好的答案,正如 scott 提到的。
testString exists within the scope of testClosure, and therefor the testString is a global variable so far as your timer is concerned.
How do JavaScript closures work?
has better answers, as scott mentions.