returnTrue and returnFalse functions in jQuery source

前端 未结 2 1695
谎友^
谎友^ 2021-02-07 22:47

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(         


        
相关标签:
2条回答
  • 2021-02-07 23:00

    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

    0 讨论(0)
  • 2021-02-07 23:24

    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.

    0 讨论(0)
提交回复
热议问题