了解JS函数语法(我敢肯定,也适用于其他语言)



这里有一些代码。这些评论是我现在所理解的。

//Whenever the cursor moves on the document, 
//execute function(e), e = undefined at the moment. And what is it doing there anyway? :P
document.onmousemove = function(e) {
//The variable event gets the value of e 
//(undefined is falsy, so not that) OR that of window.event, 
//which is true and contains lots of info on cursor position and other stuff.
var event = e || window.event;
//Record the value of the clientX key from the window.event array to variable  
//window.mouseX (why window.? with just mouseX, nothing gets recorded)
window.mouseX = event.clientX;
//Same as above for vertical position
window.mouseY = event.clientY; 
}

该代码将鼠标x/y位置分别分配给window.mouseX和mouseY。

我正在寻找的答案是:

1) 为什么要将一个未定义的变量传递到函数中,只是为了将其与已知为true的变量进行比较(至少在所有情况下,如果window.event为false,为什么会很重要,因为这样我们的函数就不会被调用,因为它绑定到document.ommousemove?)

2) 为什么X/Y鼠标位置记录在window.mouseX中而不仅仅是mouseX、鳄鱼或花生中很重要?

请用你的(对代码的评论)指导我完成这项工作。非常感谢。

为什么要将一个未定义的变量传递到函数中,只是为了将其与已知为true的变量进行比较(至少在所有情况下,如果window.event为false,为什么会很重要,因为这样我们的函数就不会被调用,因为它绑定到document.ommousemove?)

e应始终在浏览器响应事件触发调用事件处理程序时定义。

测试它是否没有定义并回退到全局事件对象,是为了与标准化之前真正古老的浏览器向后兼容。

为什么X/Y鼠标位置记录在window.mouseX中而不仅仅是mouseX、鳄鱼或花生中很重要?

以这种方式编写代码可以让阅读代码的人非常清楚地看到,正在设置全局。没有歧义的空间,所以维护代码的人不必花时间查看变量的声明位置。

相关内容

最新更新