【发布时间】:2010-12-18 10:42:22
【问题描述】:
我已经使用 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();
【问题讨论】:
-
好问题...我想这取决于
setTimeout是否本质上是异步的,以及setTimeout是否具有某种特殊属性,可以在启动时保留所需的信息超时部分,然后在执行时使用它...
标签: javascript scope closures