从documentation:
Code executed by setTimeout() is run in a separate execution context to the function from which it was called. As a consequence, the this keyword for the called function will be set to the window (or global) object; it will not be the same as the this value for the function that called setTimeout.
:
在两个示例中,超时码的范围是全球范围内,或window
。
在第一个示例中,上下文无关紧要,因为obj.style.display
在触发超时之前不进行评估。那时候,obj
有最初传递给dismiss
的任何值,并且一切正常。
在第二个示例中,代码立即执行,其中在全局window
范围内的obj
未定义(或者如果已定义,则此时不是您所期望的),因此您已生成此代码代码:
function dismiss(obj) {setTimeout(function() { undefined = "none" }, 20);}
我猜是因为它没有捕获闭包并在全局范围内执行。 –
_Why为什么这么做?_ - 因为在第一个版本中,匿名函数创建一个闭包,因此在本地作用域中保留对“obj”的引用,而第二个在全局对象的作用域中运行。 – CBroe
其实这两个工作适用于我在Firefox 38.0.5 – AlliterativeAlice