I'd like to understand the jQuery plugin syntax

前端 未结 7 1026
遇见更好的自我
遇见更好的自我 2020-11-28 18:39

The jQuery site lists the basic plugin syntax for jQuery as this:

(function( $ ){    
  $.fn.myPlugin = function() {      
    // there\'s no need to do $(th         


        
7条回答
  •  [愿得一人]
    2020-11-28 19:16

    function(x){ 
        x...
    }
    

    is just a function without a name, that takes one argument, "x", and does things with x.

    Instead of 'x', which is a common variable name, you can use $, which is a less common variable name, but still legal.

    function($){ 
        $...
    }
    

    I'll put it in parentheses to make sure it parses as an expression:

    (function($){
        $....
    })
    

    To call a function, you put () after it with a list of arguments. For example, if we wanted to call this function passing in 3 for the value of $ we would do this:

    (function($){
        $...
    })(3);
    

    Just for kicks, let's call this function and pass in jQuery as a variable:

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

    This creates a new function that takes one argument and then calls that function, passing in jQuery as the value.

    WHY?

    • Because writing jQuery every time you want to do something with jQuery is tedious.

    WHY NOT JUST WRITE $ = jQuery?

    • Because someone else might have defined $ to mean something else. This guarantees that any other meanings of $ are shadowed by this one.

提交回复
热议问题