为什么我不能传递“window.location.reload”作为setTimeout的参数? [英] Why can't I pass "window.location.reload" as an argument to setTimeout?
问题描述
我想了解一下我在Safari和Chrome中看到的错误,通过以下代码行:
I would love some insight into the error I am seeing in Safari and Chrome with the following line of code:
setTimeout(window。 location.reload,250);
Chrome报告:
未捕获TypeError:
Chrome reports:
Uncaught TypeError: Illegal invocation
和Safari:
TypeError:Type error
在FireFox中,代码运行正常。此外,此代码在三个浏览器中的每一个都运行良好:
In FireFox, the code runs fine. Also, this code runs fine in each of the three browsers:
setTimeout((function() {
window.location.reload();
}), 250);
Chrome和Safari对此代码没有问题:
Chrome and Safari have no issues with this code:
var say_hello = function () { alert("hello") };
setTimeout(say_hello, 250);
有什么特别之处window.location.reload
会导致此错误?
(不确定它是否有用,但这里有一个 jsfiddle 说明此)
(not sure if it's useful or not, but here's a jsfiddle illustrating this)
推荐答案
因为 reload c $ c>需要
window.location
为 this
。换句话说 - 它是一个 window.location
的方法。当你说:
Because reload()
needs window.location
as this
. In other words - it is a method of window.location
. When you say:
var fun = window.location. reload;
fun();
您正在调用 reload任何
此
引用(或隐式窗口
引用)。
You are calling reload()
function without any this
reference (or with implicit window
reference).
这应该工作:
setTimeout(window.location.reload.bind(window.location), 250);
window.location.reload.bind(window.location) code>部分表示:获取
window.location.reload
函数并返回一个函数,当调用时,将使用 window.location
中的
引用
。
The window.location.reload.bind(window.location)
part means: take window.location.reload
function and return a function that, when called, will use window.location
as this
reference inside reload()
.
这篇关于为什么我不能传递“window.location.reload”作为setTimeout的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!