Two methods for developing plug ins: jquery.fn.extend and jquery.extend

  • 2020-03-29 23:55:24
  • OfStack

JQuery provides two methods for developing plug-ins, which are:

JavaScript code

JQuery. The extend (object); To extend the jQuery class itself. Add new methods to the class.

JQuery. Fn. The extend (object); Add methods to jQuery objects.

What is fn. If you look at the jQuery code, it's not hard to see.

JavaScript code
jQuery.fn = jQuery.prototype = { 

   init: function( selector, context ) {// ... .  

   // ...  


JQuery. Fn = jQuery. Prototype.

Although javascript does not have a clear concept of classes, it is more convenient to understand them in terms of classes.

JQuery is a very well encapsulated class, for example, we use the statement $(" #btn1 ") to generate an instance of a jQuery class.

JQuery. The extend (object); Adding a class method to a jQuery class can be interpreted as adding static methods. Such as:


  add:function(a,b){return a+b;} 


Add a "static method" called add to jQuery, and then you can use this method where jQuery was introduced,
JavaScript code
$.add(3,4); //return 7 

JQuery. Fn. The extend (object); The extension to jquery.prototype is to add a "member function" to the jQuery class. Instances of the jQuery class can use this "member function."

Let's say we want to develop a plug-in that makes a special edit box, and when it's clicked, we alert the current edit box. Here's how:
JavaScript code






$( " #input1 " ).alertWhileClick(); //On the page: <Input the id = "input1" type = "text" />

$(" #input1 ") is an instance of jQuery that extends when it calls the member method alertWhileClick, and each time it is clicked it pops up the contents of the current edit.

In the real development process, of course, we won't make such a small white plug-in, in fact, jQuery has raised rich operation documents, events, CSS,Ajax, effect methods, combined with these methods, you can develop a more Niubility plug-in.


Another special point here is that at the beginning of the function, there is jQuery. Extend = jQuery. Fn. Extend, and jQuery. Prototype has been assigned to jQuery. The call to jQuery. Extend () does not extend the method to an instance of the object, and the method that references it is also implemented through a jQuery class, such as jquery.init (), whereas the call to jQuery

Related articles: