What does this Javascript code mean? [duplicate]
Possible Duplicate:
What does “options = options || {}” mean in Javascript?
Looking at the YouTube source...
var yt = yt || 开发者_C百科{};
Does that mean.. set yt
to yt
if yt
exists, else create a new object?
If that's the case, I didn't think you can put a condition when declaring a variable.
Assign the value of yt
back to yt
unless it is any of 0
, NaN
, false
, null
, ""
, or undefined
(i.e. it's falsy), in which case assign {}
to yt
.
This works because each of the values in the list above evaluate to false
in a boolean expression.
It means exactly that: If the content does not evaluate to false, assign it to itself (which is a neutral operation), otherwise create a new object and assign it to yt
. It's typically used to instantiate objects to use as namespaces, first checking if the namespace already exists.
Evaluate yt
, if it evaluates falsey, then instantiate it as an object.
The first time I saw somthing like this was :
function handleEvent(e){
e=e||window.event;
}
pretty nifty~ anyone know of other languages that support this syntax? (Not PHP =(
Yes, the whole right side of the expression is evaluated first before the assignment. So if yt==false
the value of the expression on the RHS will be {}
and get passed to the var yt
精彩评论