为什么 setTimeout(location.reload) 会抛出 TypeError? [英] Why does setTimeout(location.reload) throw a TypeError?

查看:59
本文介绍了为什么 setTimeout(location.reload) 会抛出 TypeError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解这段代码的奇怪行为:

I'm trying to understand the strange behavior of this code:

window.setTimeout(window.location.reload, 200);

  • 在 Firefox 中,这会引发 TypeError:

    • In Firefox this throws a TypeError:

      TypeError: 'reload' 在没有实现接口 Location 的对象上调用.

      TypeError: 'reload' called on an object that does not implement interface Location.

    • 在 Chromium 中,这会引发另一个 TypeError:

    • In Chromium this throws another TypeError:

      未捕获的类型错误:非法调用

      Uncaught TypeError: Illegal invocation

    • 这两个替代方案工作正常:

      These two alternatives work fine:

      • window.setTimeout('window.location.reload()', 200);
      • window.setTimeout(function(){window.location.reload()}, 200)

      为什么?

      推荐答案

      这是因为window.location.reload会脱离上下文调用,所以实际函数reload() 没有对 location 对象的任何引用.

      This is due to the fact that window.location.reload will be called out of context, so the actual function reload() does not have any reference to the location object.

      在JavaScript中,如果你调用一个函数foo.bar(),上下文是foo,所以this指的是foo 函数内的 bar.

      In JavaScript, if you call a function foo.bar(), the context is foo, so this refers to foo within the function bar.

      但是,如果您分配 var a = foo.bar 然后调用 a()(仍然是相同的函数),它将没有上下文,因此this 将是未定义的.这就是将函数作为方法参数传递时会发生的情况.

      However, if you assign var a = foo.bar and then call a() (which is still the same function), it will have no context, so this will be undefined. This is what happens when you pass the function as a method parameter.

      解决此问题的常用方法是绑定上下文:

      The usual way to work around this issue is to bind the context:

      window.setTimeout(window.location.reload.bind(window.location), 200);
      

      这确保了该函数将始终在 window.location 的上下文中被调用,无论它如何调用.

      This ensures that the function will always be called in the context of window.location, no matter how it is called.

      Mozilla 中有一个很好的例子文档.

      这篇关于为什么 setTimeout(location.reload) 会抛出 TypeError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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