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

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

    Type 3, in order to work would have to look like this:

    (function($){
        //Attach this new method to jQuery
        $.fn.extend({     
            //This is where you write your plugin's name
            'pluginname': function(_options) {
                // Put defaults inline, no need for another variable...
                var options =  $.extend({
                    'defaults': "go here..."
                }, _options);
    
                //Iterate over the current set of matched elements
                return this.each(function() {
    
                    //code to be inserted here
    
                });
            }
        }); 
    })(jQuery);
    

    I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.

提交回复
热议问题