Skip to content Skip to sidebar Skip to footer

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;

Solution 1:

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() { returntrue; }; // correct

Also, writing:

someProperty: returnTrue,

Is more convenient than writing:

someProperty: function(){
    returntrue;
},

Especially since they are called quite often.

Solution 2:

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() { returnthis._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

Post a Comment for "Returntrue And Returnfalse Functions In Jquery Source"