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

Source: Internet
Author: User

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

There are two types of jquery plugin development:

One is the development of a class-level plug-in that adds a new global function to jquery, which is equivalent to adding a method to the jquery class itself. The global function of jquery is a function that belongs to the jquery namespace. The other is the object-level plug-in development, that is, to add a method to the jquery object, the following two types of function development to do a detailed description.

1. Class-level plug-in development

The most straightforward understanding of plug-in development at the class level is to add a class method to the jquery class, which can be understood as adding a static method. A typical example is the $.ajax () function, which defines the function in the jquery namespace. Plug-in development at the class level can be extended in the following ways:

1.1 Adding a new global function

To add a new global function, we just need to define the following:

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

1.2 Adding multiple global functions

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}

Called when it is the same as a function: Jquery.foo (); Jquery.bar (); The shorthand form is: $.foo (); $.bar ("Bar");

1.3 Adding a global function using Jquery.extend (object)

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 the jquery namespace, we prohibit the use of JavaScript function names and variable names. However, it is still inevitable that some function names or variable names will conflict with other jquery plugins, so we are accustomed 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 function that takes the namespace is still the global function, the method that is used when calling:

JQuery.myPlugin.foo ();

JQuery.myPlugin.bar ("Bar");

The shorthand form is:

$.myplugin.foo ();

$.myplugin.bar ("Bar");

With this technique (using a separate plug-in name), we can avoid collisions of functions within namespaces.

2. Object-level plug-in development

The object-level plug-in development takes the following two forms:

Form 1:

1 (function ($) {2     $.fn.pluginname = function () {3          ///plugin code is written here 4      }5}) (JQuery);    

The above defines a jquery function, the parameter is $, after the function definition is completed, the jquery argument is passed in, immediately invoke execution, the advantage is that when we write the jquery plug-in, we can also use this alias, and do not cause conflict with prototype.

2.1 Declaring a name under the jquery namespace

This is a single plug-in script, if your script contains multiple plugins, or inverse plug-ins (for example: $.fn.dosomething () and $.fn.undosomething ()), then you need to declare multiple function names. However, usually when we write a plugin, we try to use only one name to contain all of its contents, such as the following plugin:

1 $.fn.hilight = function () {2      //Our plugin is written here 3};    

Our plug-in is called by this way:

1 $ ("mydiv"). Hilight ();

But when we need to break down our code into multiple functions, we need to break the functionality into multiple functions without adding extra namespaces. Since the realization and use of functions is the most basic class object in JS, we can do this, just like other objects, functions can be formulated as properties, so we have declared "Hilight" as a Property object of jquery, any other property or function we need to expose, can be in the " The attribute is declared in the Hilight function.

2.2 Accept the options parameter shift control plug-in behavior

Let's add functionality to our plug-ins: specifying the foreground and background colors, we might let the option pass to the plug-in function like an options object, for example:

1//Plugin definition 2 $.fn.hilight = function (options) {3    var defaults = {4       foreground: "Red", 5       Backgrou Nd: "Yellow" 6    };   7//According to the provided extension we can the options 8 var opts = $.extend (defaults, options); 9//plugin content is written here 10}    

Our plug-in can be called this way:

$ ("mydiv"). Hilight ({   foreground: "Blue"})

2.3 Exposing the default settings for plugins

One of the improvements we made to the above code was to expose the default settings for plugins, which would make it easier for plug-ins to overwrite and modify plugins with less code, and then we began to take advantage of 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 are an empty object, which 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 = {Ten     foreground: "Red", 11
   background: "Yellow"    12};

Now the user can include such a line of code in their script:

This only needs to be called once and does not necessarily call $.fn.hilight.defaults.foreground = "Blue" in the Ready Block;

Next we use the plug-in method like this, as a result it sets the blue foreground color:

$ ("mydiv"). Hilight ();

2.4 Integration

Here's the code to get our example done:

 1//Create a closure 2 $ (function ($) {3///plug-in definition 4 $.fn.hilight = function (options) {5//Build main options before Eleme NT Iteration 6 var opts = $.extend ({},$.fn.hilight.defaults.options); 7//iteration and Reformar each matched element 8 return This.each (function () {9 $this = $ (this);//Bui LD element specific OPTIONS11 var o = $.meta?   $.extend ({}, OPTs, $this. Data ()): opts;     $this. css ({backgroundcolor:o.background, Color:o.foreground 15});     var markup = $this. HTML ();     +//Call our Format function markup = $.fn.hilight.format (markup);     $this. HTML (markup);     20});     21};        22//Private Function: Debugging functions Debug ($obj) {window.console && Window.console.log) 25     Window.console.log (' Hilight selection count: ' + $obj. Size ());     26}; 27//Define exposure Format Function $.fn.hilight.format = function (txT) {return ' <strong> ' + txt + ' </strong> ';     30}; 31//Plugin Defaults $.fn.hilight.defaults = {foreground: ' Red ', background: ' Yellow ' 3             5};36}) 37}38//closure end of the pack}) (JQuery);

3 , Summary

jquery has two methods for developing plug-ins, namely:

JQuery.fn.extend (object); Adds a method to a jquery object.
Jquery.extend (object); To extend the jquery class itself. Adds a new method to the class.

3.1 JQuery.fn.extend (object);

What's the FN thing? If you look at the jquery code, it's not hard to find.

Jquery.fn = Jquery.prototype = {

Init:function (Selector, context) {//....

//......

};

The original Jquery.fn = Jquery.prototype. It's certainly not strange to prototype. Although JavaScript does not have a clear class concept, it is more convenient to use a class to understand it. jquery is a well-encapsulated class, such as we use the statement $ ("#btn1") to generate an instance of the jquery class.

JQuery.fn.extend (object); The extension to Jquery.prototype is to add "member functions" to the jquery class. An instance of the jquery class can use this "member function".

$.fn refers to the jquery namespace, plus the methods and properties on the FN, which are valid for each jquery instance, such as extending $.FN.ABC () to extend an ABC method to jquery, then each subsequent jquery instance can refer to this method.

You can do this: $ ("mydiv"). ABC ();

For example, we want to develop a plugin, make a special edit box, when it is clicked, then alert the contents of the current edit box. You can do this:

$.fn.extend ({             alertwhileclick:function () {                $ (this). "Click (function () {                    alert (this). Val ());}                 );}       } );   $ ("#input1"). Alertwhileclick (); On the page: <input id= "INPUT1" type= "text"/>

$ ("#input1") is a jquery instance, and when it calls the Member method Alertwhileclick, it implements the extension, which pops up the contents of the current edit each time it is clicked.

3.2 Jquery.extend (object); 

Adding a class method to the jquery class can be understood as adding a static method. Such as:

$.extend ({

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

});

Adds a "static method" for jquery to add, which can then be used in a place where jquery is introduced.

$.add (3,4);

Return 7

Tags: web front end, JS

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

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.