这是什么意思..." var evt = event || window.event;" [英] What is the meaning of this..."var evt=event||window.event;"
问题描述
以下JavaScript中的含义是什么?
What does the following mean in JavaScript?
var evt=event||window.event;
推荐答案
这意味着变量 evt
分配给 event
的值,或者如果 event
未定义,则分配给它值 window.event
。
It means that the variable evt
is assigned to the value of event
or if event
is undefined it is assigned the value of window.event
.
这是如何工作的,在javascript中,布尔运算符不会计算为true或者为false,而是求值为最后一个非falsy *或falsy值的对象的值。
How this works is that in javascript, boolean operators don't evaluate to true or false but instead evaluates to the value of the last object that is not falsy* or the falsy value.
因此语句首先计算表达式事件|| window.event
。如果 event
为true,则表达式不需要再进行评估,因为OR只需要一个成员为真。因此返回事件
的值。如果事件
是假的,那么需要评估OR运算符的右侧以确定结果是否为假。在这种情况下,如果 window.event
不是假的,则返回其值。
So the statement first evaluates the expression event || window.event
. If event
is true then the expression does not need to be evaluated any further since an OR only needs one member to be true. Therefore the value of event
is returned. If event
is falsy then the the right side of the OR operator needs to be evaluated to determine if the result is false. In which case, if window.event
is not falsy then its value is returned.
这是一个非常常见的用于从事件处理程序获取事件对象的习惯用法。在符合标准的浏览器上,事件对象作为第一个参数传递给事件处理程序。但是在IE上,事件对象是一个全局变量。由于历史原因,所有全局变量都是窗口对象的成员。
This is a very common idiom to get the event object from event handlers. On standards compliant browsers, the event object is passed as the first parameter to the event handler. But on IE the event object is a global variable. And for historical reasons, all global variables are members of the window object.
所以代码看起来应该是这样的:
So the code should look something like this:
element.onclick = function (event) {
var evt = event || // use the value of event if available or
window.event;// if not assume it's IE and use window.event
/* ... */
}
注意:* javascript中的* falsy值为:false,0,null和undefined。
Note: * falsy values in javascript are: false, 0, null and undefined.
这篇关于这是什么意思..." var evt = event || window.event;"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!