How to correctly use alert with apply in JavaScript?

Viewed 109

I wonder whether the JavaScript alert function in the browser needs the document as this parameter or not. So what is the correct call via apply?

/* Variant 1 */
alert.apply(null, ["Hello World!"])

/* Variant 2 */
alert.apply(window, ["Hello World!"])

An answer to the above question might also discuss bind and call, but I would be already happy if somebody could enlighten the apply case.

Edit 25.06.2021:
It seems that alert is not "normal", I get inside some fiddle:

/* Variant 3 */
alert.apply(document, ["Hello World!"]);
-->
Error: 'alert' called on an object that does not implement interface Window.
1 Answers

You can use any of these:

alert.apply(window,    ["Hello word"]);
alert.apply(null,      ["Hello world"]);
alert.apply(undefined, ["Hello world"]);

The reason you can use any of those is that alert is (effectively) defined in loose mode,¹ which means it can't have null or undefined as this; so if you call it passing null or undefined as this, the default this (window on browsers, roughly) is used instead.

You can't use document because per specification alert uses this (to see whether it can show dialogs for the window). So it needs this to be the window, not the document.


¹ loose mode (also called sloppy mode by people who don't care about parallel construction) is the opposite of strict mode. Code is in loose mode unless you use modules, class, or "use strict";.

Related