Why does this not work?
setTimeout(window.location.reload, 1000)
This does
setTimeout(() => window.location.reload(), 1000)
The first parameter is a function. Shouldn't the first example work?
Why does this not work?
setTimeout(window.location.reload, 1000)
This does
setTimeout(() => window.location.reload(), 1000)
The first parameter is a function. Shouldn't the first example work?
The problem is that you are passing a loose reference to the reload
function; therefore, losing its binding to window.location
.
You can use the following to prove the point (It may not work
setTimeout(window.location.reload.bind(window.location), 1000)
But I think adding a function wrapper makes it easier to understand.
Example
const a = {
value: 2,
b: function() {
console.log(this.value);
}
}
a.b();
const b = a.b;
b();
const boundB = b.bind(a);
boundB();
Summary
Using syntax like a.b()
makes sure that b
is called with a
as its this
.
Calling a function without a .
before will the function as a global, which will pass window
as this in sloppy mode and null
as this
in strict mode.
This can always be overriden by binding function or by using arrow functions (which take its this
from the surrounding this
) or if you bind your function ahead of time.
It won't work as the scope of calling window.location.reload
will be window
instead of window.location
.
Try this:
window.location.reload.call(window);
vs.
window.location.reload.call(window.location);
This post sums it up nicely https://stackoverflow.com/a/10840058/10853009
Because
reload()
needswindow.location
asthis
. In other words - it is a method ofwindow.location
. When you say:
var fun = window.location.reload;
fun();
You are calling
reload()
function without anythis
reference (or with implicitwindow
reference).