Javascript alert 和 window.alert 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13459907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:09:17  来源:igfitidea点击:

What is the difference between alert and window.alert?

javascript

提问by scdmb

What is the difference between alert()and window.alert()functions? It seems to work the same.

alert()window.alert()函数有什么区别?它似乎工作相同。

回答by Kevin Boucher

Because windowis the global object, you can call an alerteither by it's shorthand: alert( 'Hello!' );or by referencing the global object specifically: window.alert( 'Hello!' );

因为window是全局对象,您可以alert通过它的简写来调用 an :alert( 'Hello!' );或者通过专门引用全局对象:window.alert( 'Hello!' );

They are the same.

他们是一样的。

回答by Eineki

They are usually the same thing but, if in your scope, see example, the alert function got redefined then alert and window.alert will not be the same function.

它们通常是相同的,但是,如果在您的范围内,请参见示例,重新定义了 alert 函数,则 alert 和 window.alert 将不是同一个函数。

(function () {
    function alert(test) {
        document.write(test);
    }

    alert("hello page");
   window.alert("hello world");
})()

Hope the example will shed more light on this subject than my explanation.

希望这个例子比我的解释更能说明这个问题。

You can also shadow the function name with a variable and obtain an error when calling it.

您还可以使用变量隐藏函数名称并在调用它时获取错误。

(function () {
    var alert;
    alert("Why don't you work, silly function?");
})()