jQuery and Twitter Bootstrap function explanation

后端 未结 3 1774
無奈伤痛
無奈伤痛 2021-01-07 01:55

If you see the twitter\'s bootstrap application.js file that exists in all documents, you will notice something the following code:

!function( $ ) {
    ...
         


        
相关标签:
3条回答
  • 2021-01-07 02:13

    This guarantees that in the code inside the function you will be able to use the $ shorthand way of accessing jQuery. In some environments (Wordpress for example), they don't have the $ shorthand "enabled" to avoid conflict with other javascript libraries. By using this way here, you can use the simple $ construct in any environment (as long as window.jQuery is defined).

    So, basically it creates a function and immediately calls it, passing in window.jQuery. That means code in the function will see the $ local variable, and it's been assigned window.jQuery.

    0 讨论(0)
  • 2021-01-07 02:14

    It's a self executing function:

    !function(x){}(y)
    

    x is the parameter of the function and y is the parameter you pass in the auto-call of that function.

    ! is just a visual guide that tells you at a glance that the function is self executing. Another common practice is to wrap it in parenthesis instead. (function(){}())

    0 讨论(0)
  • 2021-01-07 02:25

    That is because

    function($) {} (window.jQuery);
    

    is not valid in syntax, but

    !function($) {} (window.jQuery);
    

    is valid.

    Now the question is why the first case is invalid?

    Let's first take look at this. Both anonymous functions and named functions can be considered as a expression, e.g.

    0 + function(y) { return y; } (1);
    0 + function x(y) { return y; } (1);
    

    are both valid.

    Then consider this situation, this statement contain one expression

    function x(y) {
        return y;
    }
    (1);
    

    "That's incorrect!" may you say that because you know they are actually one function definition and one statement with one expression (1).

    The truth is, those codes is ambiguous to a grammar parser, because it could be resolved as either one function and one parenthesis-wrapped expression, or a function invocation. To avoid this kind of ambiguous, Javascript rules that if function occurs as the first token of a statement, the statement ought to be a function definition. So function($) {} (window.jQuery); is not valid in syntax because it's not a valid function definition. But prepose a ! or even this kind code is valid

    0 + function x(y) {
        return y;
    }
    (1);
    

    It's one statement, with a binary plus, whose rhs is the function invocation, inside it.

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