Why is it that I can do this:
$("button").on('click', function(){window.history.back();});
however, when I try;
$("button").on('click', window.history.back);
/*or*/ $("button").on('click', history.back);
I get:
Uncaught TypeError: Illegal invocation
at HTMLAnchorElement.dispatch (jquery-1.12.4.js:5226)
at HTMLAnchorElement.elemData.handle (jquery-1.12.4.js:4878)
I was under the impression that when there is no retained context it defaults to the window object, which would allow me to do this?
First of all, history.back()
must be invoked with history
as the context, if it defaults to window
it will throw the error you describe. The issue here though is that jQuery invokes the handler with the element that has the event listener bound.
Your first line of code works because context is irrelevant to the anonymous function you pass as a handler. The fact that jQuery sets the element as the context doesn't matter since you correctly invoke history.back()
inside of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With