开发者

var foo = foo || alert(foo);

开发者 https://www.devze.com 2023-01-28 01:56 出处:网络
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.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消