I'd like to understand the jQuery plugin syntax

前端 未结 7 1027
遇见更好的自我
遇见更好的自我 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:18


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

    That is self-executing anonymous function that uses $ in argument so that you can use it ($) instead of jQuery inside that function and without the fear of conflicting with other libraries because in other libraries too $ has special meaning. That pattern is especially useful when writing jQuery plugins.

    You can write any character there instead of $ too:

    (function(j){
      // can do something like 
      j.fn.function_name = function(x){};
    
    })(jQuery);
    

    Here j will automatically catch up jQuery specified at the end (jQuery). Or you can leave out the argument completely but then you will have to use jQuery keyword all around instead of $ with no fear of collision still. So $ is wrapped in the argument for short-hand so that you can write $ instead of jQuery all around inside that function.

    If you even look at the source code of jQuery, you will see that everything is wrapped in between:

    (function( window, undefined ) {
      // jQuery code
    })(window);
    

    That is as can be seen also a self-executing anonymous function with arguments. A window (and undefined) argument is created and is mapped with global window object at the bottom (window). This is popular pattern these days and has little speed gain because here window is will be looked into from the argument rather than global window object which is mapped below.


    The $.fn is jQuery's object where you create your new function (which is also an object) or the plugin itself so that jQuery wraps your plugin in its $.fn object and make it available.


    Interestingly, I had answered similar question here:

    JavaScript / jQuery closure function syntax

    You can also check out this article to know more about self-executing functions that I had written:

    Javascript Self-executing Functions

提交回复
热议问题