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

前端 未结 6 915
灰色年华
灰色年华 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:35

    At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. What this means is that you have defined a function and you are calling it immediately.

    This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal).

    A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). Hence:

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

    Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal.

    Type 1 isn't really a plugin. You're simply assigning an object literal to jQuery.fn. Typically you assign a function to jQuery.fn as plugins are usually just functions.

    Type 2 is similar to Type 1; you aren't really creating a plugin here. You're simply adding an object literal to jQuery.fn.

    Type 3 is a plugin, but it's not the best or easiest way to create one.

    To understand more about this, take a look at this similar question and answer. Also, this page goes into some detail about authoring plugins.

提交回复
热议问题