Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returnTrue and returnFalse functions in jQuery source

I can't help but notice there are two seemingly useless functions in the source code of jQuery (For v1.9.1, it's line 2702 and line 2706):

function returnTrue() {
    return true;
}

function returnFalse() {
    return false;
}

Which both are called quite often within jQuery. Is there a reason why they don't simply substitute the function call with a boolean true or false?

like image 303
rexcfnghk Avatar asked Feb 07 '13 07:02

rexcfnghk


2 Answers

If an object property, function argument, etc expects a function you should provide a function not a boolean.

For example in vanilla JavaScript:

var a = document.createElement("a");
a.href = "http://www.google.com/";
/*
 * see https://developer.mozilla.org/en-US/docs/DOM/element.onclick
 * element.onclick = functionRef;
 * where functionRef is a function - often a name of a function declared 
 * elsewhere or a function expression.
 */
a.onclick = true;                        // wrong
a.onclick = returnTrue;                  // correct
a.onclick = function() { return true; }; // correct

Also, writing:

someProperty: returnTrue,

Is more convenient than writing:

someProperty: function(){
    return true;
},

Especially since they are called quite often.

like image 184
Salman A Avatar answered Nov 15 '22 21:11

Salman A


it was used like this:

stopImmediatePropagation: function() {
    this.isImmediatePropagationStopped = returnTrue;
    this.stopPropagation();
}

here isImmediatePropagationStopped is a query method. used like this event.isImmediatePropagationStopped()

of course, you can define a instance method, like:

event.prototyoe.isImmediatePropagationStopped = function() { return this._isImmediatePropagationStopped };

stopImmediatePropagation: function() {
    this._isImmediatePropagationStopped = true; //or false at other place.
    this.stopPropagation();
}

but you have to introduce a new instance property _isImmediatePropagationStopped to store the status.

with this trick, you can cut off bunch of instance properties for hold true/false status here, like _isImmediatePropagationStopped, _isDefaultPrevented etc.

so that, in my opinion, this is just a matter of code style, not right or wrong.

PS: the query methods on event, like isDefaultPrevented , isPropagationStopped, isImmediatePropagationStopped are defined in DOM event level 3 sepc.

spec: http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-Event-isImmediatePropagationStopped

like image 29
Rain Diao Avatar answered Nov 15 '22 22:11

Rain Diao