從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