What does (function($) {})(jQuery); mean?

前端 未结 6 824
灰色年华
灰色年华 2020-11-22 08:38

I am just starting out with writing jQuery plugins. I wrote three small plugins but I have been simply copying the line into all my plugins without actually knowing what it

6条回答
  •  死守一世寂寞
    2020-11-22 09:41

    Actually, this example helped me to understand what does (function($) {})(jQuery); mean.

    Consider this:

    // Clousure declaration (aka anonymous function)
    var f = function(x) { return x*x; };
    // And use of it
    console.log( f(2) ); // Gives: 4
    
    // An inline version (immediately invoked)
    console.log( (function(x) { return x*x; })(2) ); // Gives: 4
    

    And now consider this:

    • jQuery is a variable holding jQuery object.
    • $ is a variable name like any other (a, $b, a$b etc.) and it doesn't have any special meaning like in PHP.

    Knowing that we can take another look at our example:

    var $f = function($) { return $*$; };
    var jQuery = 2;
    console.log( $f(jQuery) ); // Gives: 4
    
    // An inline version (immediately invoked)
    console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4
    

提交回复
热议问题