What does the following mean in JavaScript?
开发者_如何学Govar evt=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
.
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.
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.
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
/* ... */
}
Note: * falsy values in javascript are: false, 0, null and undefined.
The code is a hack because Microsoft decided to put their events in the global window.event
instead of passing it as a parameter to the event function.
So, this code will attempt to set evt
to the event passed in (which will work for the non-Microsoft browsers) and, if that turns out to be null
(as it will be for Microsoft browsers), it will then grab it from the global.
From that point on, your function can just use evt
disregarding browser differences (well, at least those relating to events).
var evt=event||window.event;
The code above is a shortcut to a IF ELSE statement, and is equivalent to the bellow code:
var evt = "nothing valuable yet";
if ( event ) {
evt = event;
} else {
evt = window.event;
}
Two IF ELSE shortcuts in Javascript:
var resultIsTrue = true || false; // if first value is true, return first value
var resultIsFalse = true && false; // if first value is true, return second value
精彩评论