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

I am trying to understand the strange behavior of this code:

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

    TypeError: 'reload' throws an object that does not implement the interface layout.

  • In Chromium, this raises another TypeError:

    Uncaught TypeError: illegal call


These two alternatives work fine:

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

Why?

+4
source share
1 answer

This is because it window.location.reloadis called from the context, so the actual function reload()does not have an object reference location.

In JavaScript, if you call a function foo.bar(), the context footherefore thisrefers to fooin the function bar.

, var a = foo.bar, a() ( ), , this undefined. , , .

- :

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

, window.location, , .

Mozilla .

+4

Source: https://habr.com/ru/post/1654107/


All Articles