What is the consequence of this bit of javascript?

前端 未结 4 1581
清酒与你
清酒与你 2020-12-06 02:16

I was looking at the jQuery UI code, and I found that every file starts with a construct like this:

jQuery.ui || (function($) {

My question

4条回答
  •  一整个雨季
    2020-12-06 03:00

    I'm guessing the ; is to ensure that javascript packers won't mess up the line, but that's the best I have.

    The logical or is there to make sure that jQuery.ui doesn't get declared twice. JavaScript does short circuit, so it won't evaluate the right hand side of the || if the left hand side evaluates to something that is truthey (thanks JP!).

    Bonus syntax deciphering, that $ that's passed in to the anonymous function is the reference to jQuery. I had to scroll all the way down the page before that one clicked :-)

    So, here's a broken down version of the line above

    ;              // extra semi colon to ensure correct concatenation and minifying
    jQuery.ui      // check if the variable called jQuery.ui is truthey
    ||             // OR if jQuery.ui isn't defined
    (function($) {...})(jQuery); // define and execute an anonymous function
                                 // passing in the conflict safe jQuery
                                 // as the parameter called $
    

提交回复
热议问题