Why can't I pass "window.location.reload" as an argument to setTimeout?
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();
You are calling reload()
function without any this
reference (or with implicit window
reference).
This should work:
setTimeout(window.location.reload.bind(window.location), 250);
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()
.
See also
- How can I pass an argument to a function called using setTimeout?
- Why doesn't console.log work when passed as a parameter to forEach?
- Preserve 'this' reference in javascript prototype event handler
Because this
must be bound to location
when you call reload
. It's same as trying:
var reload = window.location.reload;
reload();
this
would be window
in non-strict mode and undefined
in strict mode which are both invalid.
in non-old browsers you can do instead:
reload.call( location )
or in your example:
setTimeout( window.location.reload.bind( window.location ), 1000 )
Older IEs don't support explicit binding on host objects though.
You also get this for some native methods which are not generic such as:
var a = function(){}.toString;
a();
TypeError: Function.prototype.toString is not generic
Some are generic:
var fakeArray = {0:1,1:2,length:2};
fakeArray.join = [].join;
fakeArray.join( " " );
"1 2"
This fails because you're missing the location
context (the function's this
), when passing it your way.
You would have to bind
the context, before you can use it like this, for example with the underscore.js bind method
var boundReload = _.bind(window.location.reload, window.location);
setTimeout(boundReload, 500)
It's the same with any other function that is usually called from it's containing object like console.log