returnTrue and returnFalse functions in jQuery source

前端 未结 2 1696
谎友^
谎友^ 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: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.

提交回复
热议问题