Understand jquery's $. extend (), $. fn, and $. fn. extend ()

Source: Internet
Author: User

Understand jquery's $. extend (), $. fn, and $. fn. extend ()
There are two types of jquery plug-in development: one is class-level plug-in development, that is, adding a new global function to jquery is equivalent to adding a method to the jquery class itself. Jquery's global functions belong to the jquery namespace. The other is object-level plug-in development, that is, adding methods to jquery objects. The following describes the development of the two functions in detail. 1. Class-level plug-in development the most direct understanding of class-level plug-in development is to add class methods to the jquery class, which can be understood as adding static methods. A typical example is the $. ajax () function, which is defined in the namespace of jquery. You can use the following extensions for class-level plug-in development: 1.1 Add a new global function and add a new global function. We only need to define the following:

1 jQuery.foo = function() {   2 alert("This is a test.");  3 }; 

 

1.2 add multiple global functions to add multiple global functions, which can be defined as follows:
1 jQuery.foo = function(){2   alert("This is a test.");  3 };4 jQuery.bar = function(param){5     alert("This is another test.");6 }

 

The call time is the same as that of a function: jQuery. foo (); jQuery. bar (); abbreviated form: $. foo (); $. bar ("bar"); 1.3 Use jQuery. extend (object) add global functions
1 jQuery.extend({2     foo:function(){3         alert("This is a test.");    4     },5     bar:function(){6        alert("This is another test");7     }8 });      

 

1.4 using namespaces although in jQuery namespaces, javascript function names and variable names are not allowed. But it is still inevitable that some function names or variable names conflict with other jQuery plug-ins, so we are used to encapsulating some methods into another custom namespace.
1 jQuery.myPlugin = {2     foo:function(){3        alert("This is a test.");4     }  ,5    bar:function("bar"){6       alert("This is another test.");7    }  8 }

 

The namespace function is still a global function. The method used for calling is jQuery. myPlugin. foo (); jQuery. myPlugin. bar ("bar"); abbreviated form: $. myPlugin. foo (); $. myPlugin. bar ("bar"); with this technique (using an independent plug-in name), we can avoid conflicts between functions in a namespace. 2. Object-level plug-in development object-level plug-in development requires the following two forms: Form 1:
1 (function ($) {2 $. fn. pluginName = function () {3 // The plug-in code is written here 4} 5}) (jQuery );

 

The above defines a jQuery function with the form parameter $. After the function definition is complete, pass the jQuery real parameter in and call it for execution immediately. The advantage is that when we write the jQuery plug-in, you can also use the $ alias instead of causing a conflict with prototype. 2.1 declare a name in the jQuery namespace. This is a single plug-in script. If your script contains multiple plug-ins or plug-ins with mutual inversion (for example: $. fn. doSomething () and $. fn. undoSomething (), you need to declare multiple function names. However, when writing a plug-in, we usually try to use only one name to include all its content, such as the following plug-in: 1 $. fn. hilight = function () {2 // our plug-in is written here 3}; our plug-in is called like this: 1 $ ("myDiv "). hilight (); but when we need to break down our code into multiple functions, we need to break down the functions into multiple functions without adding extra namespaces. To realize and utilize functions as the most basic class objects in js, we can do this. Just like other objects, functions can be formulated as attributes, therefore, we have declared "hilight" as a jQuery attribute object. Any other attribute or function that we need to expose can be declared in the "hilight" function. 2.2 accept the action of the options parameter Shift Control plug-in. Let's add a function for our plug-in: Specify the foreground color and background color. We may pass the options to the plug-in function like an options object, example:
1 // plugin definition 2 $. fn. hilight = function (options) {3 var defaults = {4 foreground: "red", 5 background: "yellow" 6 }; 7 // according to the provided extensions, we can set options 8 var opts = $. extend (defaults, options); 9 // The plug-in content is written here 10}

 

Our plug-in can be called like this: $ ("myDiv "). hilight ({foreground: "blue"}) 2.3 exposes the default settings of the plug-in. One of our improvements to the above Code is to expose the default settings of the plug-in, this makes it easier for plug-in users to overwrite and modify the plug-in with less code. Next we will start to use function objects.
 1 // plugin definition 2 $.fn.hilight = function(options){ 3   // extend our default options with those provided. 4   // note that the first arg to extend is an empty object , this is to keep form overriding our "defaults" object. 5   var opts = $.extend({},$options); 6 // our plugin inplementation code goes here.   7 }; 8 // plugin defaults -added as a property on our plugin function 9 $.fn.hilight.default = {10     foreground : "red",11     background:"yellow"    12 };

 

Now users can include such a line of code in their scripts: // This only needs to be called once, and does not have to be called in the ready block $. fn. hilight. defaults. foreground = "blue"; next we use the plug-in method like this, and it sets the blue foreground color: $ ("myDiv "). hilight (); 2.4 integrate the following code after our example is completed:
1 // create a closure 2 $ (function ($) {3 // plug-in Definition 4 $. fn. hilight = function (options) {5 // build main options before element iteration 6 var opts = $. extend ({}, $. fn. hilight. defaults. options); 7 // iteration and reformar each matched element 8 return this. each (function () {9 $ this = $ (this); 10 // build element specific options11 var o = $. meta? $. Extend ({}, opts, $ this. data (): opts; 12 rows this.css ({13 backgroundColor: o. background, 14 color: o. foreground 15}); 16 var markup = export this.html (); 17 // call our format function 18 markup = $. fn. hilight. format (markup); 19 export this.html (markup); 20}); 21}; 22 // Private function: debugging 23 function debug ($ obj) {24 if (window. console & window. console. log) 25 window. console. log ('hilight selection count: '+ $ obj. size (); 26}; 27 // defines the exposure format function 28 $. fn. hilight. format = function (txt) {29 return '<strong>' + txt + '</strong>'; 30}; 31 // defaults 32 $ of the plug-in. fn. hilight. defaults = {33 foreground: 'red', 34 background: 'yellow' 35}; 36}) 37} 38 // closure end 39}) (jQuery );

 

3. In summary, jQuery provides two methods for the development plug-in: jQuery. fn. extend (object); and adds methods to the jQuery object. JQuery. extend (object); adds a new method to the class to extend the jQuery class itself. 3.1 jQuery. fn. extend (object); what is fn. It is not difficult to see jQuery code. JQuery. fn = jQuery. prototype = {init: function (selector, context ){//.... //......}; jQuery. fn = jQuery. prototype. prototype is certainly not unfamiliar. Although javascript does not have a clear concept of a class, it is more convenient to use a class to understand it. JQuery is a well-encapsulated class. For example, we use the statement $ ("# btn1") to generate a jQuery class instance. JQuery. fn. extend (object); the extension to jQuery. prototype is to add "member functions" to the jQuery class ". JQuery class instances can use this "member function ". $. Fn refers to the namespace of jQuery. Adding Methods and attributes on fn will be valid for each jquery instance, such as the extension $. fn. abc () is an extension of the abc method for jquery, so every jQuery instance can reference this method. You can: $ ("myDiv "). abc (); for example, we want to develop a plug-in and create a Special edit box. When it is clicked, the content in the current edit box of alert will be displayed. You can do this:
$. Fn. extend ({alertWhileClick: function () {$ (this ). click (function () {alert ($ (this ). val () ;};}}); $ ("# input1 "). alertWhileClick (); // <input id = "input1" type = "text"/>

 

$ ("# Input1") is a jQuery instance. When it calls the member method alertWhileClick, the extension is implemented. When it is clicked, the content in the current edit is displayed. 3.2 jQuery. extend (object); adding class methods to the jQuery class can be understood as adding static methods. For example: $. extend ({add: function (a, B) {return a + B ;}}); then add a "static method" for jQuery to add ", then you can use this method in the place where jQuery is introduced $. add (3, 4); // return 7

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.