1

I'm trying to make the document reload when a button is clicked. Here's my code:

var e = document.getElementById('a');
e.addEventListener('click',location.reload);

It returns Uncaught TypeError: Illegal Invocation after e was clicked. However, the following code works and the document reloaded:

var e = document.getElementById('a');//same thing
e.addEventListener('click',function(){location.reload()});
//warp location.reload inside function -> works!

I don't understand why the first code doesn't work. Can anyone give some explanation? Thanks!

jeqcho
  • 19
  • 1
  • 1
  • 6
  • In the first case, the second argument of your eventListener is not a function – bugs Mar 31 '18 at 15:48
  • @bugs yes it is. `window.location.reload` is a function. – BenM Mar 31 '18 at 15:49
  • 2
    Possible duplicate of [Why can't I pass "window.location.reload" as an argument to setTimeout?](https://stackoverflow.com/questions/10839989/why-cant-i-pass-window-location-reload-as-an-argument-to-settimeout) – BenM Mar 31 '18 at 16:00

2 Answers2

1

When you are calling location.reload() it not only calls function, but also sets this to the value of location, so these two are equivalent:

location.reload();
location.reload.call(location);

However, when you supply it to addEventListener only function reference is stored, but not the value of this, so when it's called it's equivalent to

location.reload.call(undefined); // strict mode
location.reload.call(window); // sloppy mode

For example Firefox provides a more clear error message: TypeError: 'reload' called on an object that does not implement interface Location.

As such for proper behavior you need to create a closure, or bind this to location, so both will work:

e.addEventListener('click', function(){location.reload()});
e.addEventListener('click', location.reload.bind(location));
Andrew Svietlichnyy
  • 743
  • 1
  • 6
  • 13
-3

You're missing () from the recall function call in your first example. It should be:

var e = document.getElementById('a'); e.addEventListener('click',location.reload());

stoicamir
  • 1
  • 1
  • No. That will cause the **return value** of `location.reload` to be passed as the callback function, not the function reference itself. It'll cause the page to refresh infinitely, because the function is being called each time the page loads (to obtain its return value), not each time the button is clicked... – BenM Mar 31 '18 at 15:52