javascript - 我可以删除 var 关键字吗

标签 javascript events window coordinates

以下代码摘自“JavaScript by Example Second Edition”。

我想的代码

if (!e) var e = window.event; // Internet Explorer

应该是

if (!e) e = window.event; // Internet Explorer

你怎么看?这样对吗?或者代码应该保持原样?

<html>
<head>
    <title>Mouse Coordinates</title>
    <script type="text/javascript">
        function getCoords(e) {
            var x = 0; // x and y positions
            var y = 0;
            if (!e) var e = window.event; // Internet Explorer
            if (e.pageX || e.pageY) { // Firefox
                x = e.pageX;
                y = e.pageY;
            }
            else if (e.clientX || e.clientY) {
                x = e.clientX + document.body.scrollLeft
              + document.documentElement.scrollLeft;
                y = e.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
            }
            // x and y contain the mouse position
            // relative to the document
            alert(x + ", " + y);
        }
    </script>
    </head>
        <body>
            <div style="background-color: aqua; position: absolute; top: 50px"
                onmouseover="return getCoords(event);">
                <h1>Mouse positions are relative to the document, not the
&lt;div&gt; container</h1>
            </div>
        </body>
</html>

最佳答案

代码就目前而言是正确的,但没有 var 关键字也可以工作。

由于 e 是函数的形式参数(无论是否传递),因此无需将其声明为 var

在 MSIE 上 e 没有被传递,所以它被赋予了全局 window.event 对象的值。

请注意,var 关键字本身不会覆盖任何现有值,它仅用于声明局部范围内的变量.如果变量已经有一个值,则“提升”会将声明移动到范围的顶部,但将任何赋值保留在原处。

一个更惯用的写法是:

 function getCoords(e) {
     e = e || window.event;
     ...
 }

关于javascript - 我可以删除 var 关键字吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12578049/

相关文章:

javascript - 单击 Javascript Alert 中的按钮在新窗口中打开弹出窗口

python - 导入Gtk并关闭窗口后访问Gdk区域

javascript - 检测由于下载栏(chrome、latest edge、firefox)而导致的窗口调整大小与一般窗口调整大小

javascript - 如何在javascript中合并连续的日期?

javascript - Node.js - Express.js JWT 总是在浏览器响应中返回一个无效的 token 错误

events - 在 GWT 应用程序中,我应该使用不同的事件(和事件处理程序)来切换到每个 View 吗?

events - ZF3 - 附加到 EventManager 的事件未触发

c# - 在 XAML 中为一个事件添加多个事件处理程序?

javascript - Nodejs 中的 SOAP 客户端-服务器通信

大型项目(社交媒体)的 Javascript/jQuery 优化