如何正确使用 alert with apply in JavaScript?

How to correctly use alert with apply in JavaScript?

不知浏览器是否有JavaScript提醒功能 是否需要文档作为此参数。那么什么是 通过申请正确调用?

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

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

上述问题的答案也可能讨论绑定 并打电话,但如果有人可以,我会很高兴 启发应用案例。

编辑 25.06.2021:
似乎警报不“正常”,我进入了一些 fiddle:

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

您可以使用以下任何一种:

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

您可以使用其中任何一个的原因是 alert 是(有效地)在松散模式下定义的,¹ 这意味着它不能将 nullundefined 作为 this;因此,如果您调用它传递 nullundefined 作为 this,则使用默认的 this(在浏览器上大致为 window)。

您不能使用 document,因为 per specification alert 使用 this(查看它是否可以显示 window 的对话框)。所以它需要 this 成为 window,而不是文档。


¹ loose mode(也被不关心并行构造的人称为sloppy mode)与[=相反35=]严格模式。除非您使用模块 class"use strict";.

,否则代码处于松散模式