Why does setTimeout(location.reload) throw a TypeError? [duplicate]

我是研究僧i 提交于 2019-12-21 19:27:10

问题


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

window.setTimeout(window.location.reload, 200);
  • In Firefox this throws a TypeError:

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

  • 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)

Why?


回答1:


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.

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

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);

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

There is a nice example in the Mozilla docs.



来源:https://stackoverflow.com/questions/39407803/why-does-settimeoutlocation-reload-throw-a-typeerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!