What is the difference between the two jquery methods?

I code some jquery plugins, I extended them, but I don't know why:

Method 1

(function($){ $.fn.myplugin = function() {} })(jQuery); $.extend({myplugin : $.fn.myplugin}); 

Method 2

 (function($){ $.extend({ myplugin: function() {} }) })(jQuery); 

for # 1, I can call $ .myplugin (). myplugin2 (). myplugin3 ();

but C # 2 cannot use $ .myplugin (). myplugin2 (); it shows that myplugin2 is an invalid function


basically I want to write in # 2 because I don't need to declare

 $.extend({ myplugin : $.fn.myplugin, myplugin2 : $.fn.myplugin2, .....}); 

for each plugin. can anyone help me with this?

+4
source share
2 answers

In both cases, you add a function to the jQuery global object, which allows you to call $.pluginName .

# 1 also adds a plugin to all the jQuery element objects that you get when you call the $ : $("#selector") function.

Perhaps your plugin returns a jQuery element object. So first you use $.pluginName , and in the following code you call $.fn.pluginName . You cannot bind C # 2 calls because $.fn.pluginName is undefined.

This will make sense if you know that $.fn is an alias for $.prototype . (The prototype functions are members of all $() return values ​​— using the new keyword in the background.)


You can create an object with all your plugins to simplify the code:

 var plugins = { myPlugin: function(){}, myPlugin2: function(){} } $.extend($, plugins); $.extend($.fn, plugins); 
+1
source

$.fn.myplugin = function() {} allows you to call your function in a jquery object, for example:

 $("something").myplugin() 

Where

 $.extend({ myplugin: function() {} }) 

makes it so that you call your function as follows:

 $.myplugin() 

In your first example, you are doing both of them. The second does only the second.

+1
source

All Articles