简体   繁体   中英

Javascript: meaning of the event and function separated by OR Operator

I found a block of code in a javascript. The event and function is separated with OR operator.

    var t = document.onmouseup || function () {};

Please help me to understand the above line.

This line is to make sure that, t has a valid function, for the rest of the code.

It means that, if the document.onmouseup is already defined, assign it to t , otherwise assign the dummy function function() {}; to t . So that, later on I can do t() without worrying whether t is a function or not.

The code takes advantage of the shortcircuit evaluation of JavaScript's logical operators.

But I believe, this is not foolproof enough. I would use

var t = typeof document.onmouseup === "function" ? document.onmouseup : function () {};

The difference between both the codes is that, the code in question just makes sure that document.onmouseup has a truthy value or not. But the code proposed in this answer makes sure that the type of document.onmouseup is a function.

Check this program to understand, why the code in question might fail.

function func1() {
    return 1;
}
var t = func1 || function() {};
console.log(t());
func1 = 1;
var t = func1 || function() {};
console.log(t());

Output

1
TypeError: number is not a function

这行意味着变量t将承担document.mouseup的功能,或者,如果未定义,则使用匿名function() {} null或false。

The OR operator returns its left argument if it's truthy, otherwise it returns its right argument.

So this sets t to the mouseup handler if it's set, otherwise it sets it to a function that does nothing.

it means

var t;
if ( document.onmouseup ) {
    t = document.onmouseup ;   
} else {
    t = function () {};
}

The piece of code you found is a shorthand declaration, it is functionally equal to the following:

if(document.onmouseup)
{
    var t=document.onmouseup;
}
else
{
    var t=function(){};
}

shorthand declarations are one of the things that make javascript the powerful and usefull language it is (and the reason its one of the few languages that doesnt have elseif )

Shorthand declarations are always shorter, and in some cases actually improve readability.

consider expression ( A || B ) then its evalutation is :

if !!A is true then evaluate to A
else evaluate to B

So when you write

var t = A || B

then if !!A evaluates to true then value of t will be A else value of t will be B

Here in your example A is document.onmouseup and B is function () {}

so if document.onmouseup exists then !!document.onmouseup will be true and t will be assigned to it, else t will be assigned to function(){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM