为什么我不能传递“window.location.reload”作为setTimeout的参数? [英] Why can't I pass "window.location.reload" as an argument to setTimeout?

查看:949
本文介绍了为什么我不能传递“window.location.reload”作为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆