Can someone explain what this does?
开发者_JS百科var foo = foo || alert(foo);
If foo
is already defined and evaluates to true, it sets foo = foo
, i.e. it does nothing.
If foo
is defined but evaluates to false, it would popup whatever foo
is (false
, null
, undefined
, empty string, 0, NaN), but since alert
returns nothing, foo
will be set to undefined
.
If foo
is not yet defined, an exception will be thrown. (Edit: In your example, foo
will always be defined because of the var foo
declaration.)
If foo
evaluates to false (e.g. false, null or zero), the value after the ||
operator is also evaluated, and shows the value.
The alert
method doesn't return a value, so foo
will become undefined if it evaluated to false, otherwise it will be assigned it's own value.
var foo;
if (foo)
foo = foo;
else
foo = alert(foo); // probably undefined
精彩评论