Front-End Knowledge | On how jquery writes plugins

Source: Internet
Author: User
Tags closure

I. jquery plug-in mechanism

To make it easy for users to create plugins, jquery provides the Jquery.extend () and JQuery.fn.extend () methods
Jquery.extend (object), a parameter used to extend the jquery class itself, that is, to add a new function on the jquery class/namespace, or a static method, such as a jquery built-in Ajax method with Jquery.ajax () This is called a bit like "class name. Method Name" static method invocation.

Jquery.extend () extension
Extending the jquery object itself
Jquery.extend ({
"MinValue": function (A, b) {
Return a < b? A:B;
},
"MaxValue": function (A, b) {
Return a > B? A:B;
}
});
var i = 100; j = 101;
var Min_v = $.minvalue (i, j);

Jquery.extend () method overloading
Jquery.extend ([deep], Target, Object1, [objectn])

Parameters
Deep: Optional. If set to True, the merge is recursive.
Target: object to be modified.
Object1: The object to be merged into the first object.
OBJECTN: Optional. An object to be merged into the first object.

Example
Merge defaults and options without modifying the defaults.
var empty = {};
var defaults = {Validate:false, limit:5, Name: "foo"};
var options = {validate:true, name: "Bar"};
var settings = jquery.extend (empty, defaults, options)

Results
Settings = = {Validate:true, limit:5, Name: "Bar"}
Empty = = {Validate:true, limit:5, Name: "Bar"}

Extends an object with one or more other objects, returning the object being extended.
If target is not specified, the jquery namespace itself is extended. This helps plug-in authors add new methods to jquery.
If the first argument is set to True, jquery returns a deep copy, recursively copying any objects found. Otherwise, the copy will share the structure with the original object.
Undefined properties will not be copied, but properties inherited from the object's prototype will be copied.
Query.fn.extend (object) extends the set of jQuery elements to provide new methods (often used to make plug-ins).

First, let's see what FN is. 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, which is the prototype of the JQuery object. The JQuery.fn.extend () method is the prototype method for extending the jquery object. We know that the method of extending the prototype is equivalent to adding a "member method" to the object, the class's "member method" to the object of the class to be called, so using the JQuery.fn.extend (object) extension method, an instance of the jquery class can use this "member function", such as $ (' P '). Extend (obj).
The JQuery.fn.extend (object) and Jquery.extend (object) methods must be separated.
Two. Self-executing anonymous function/closure

    1. What is a self-executing anonymous function?
      It refers to a function such as: (function () {//code}) ();

    2. Question Why (function () {//code}), can be executed, and function () {//code} ();
      (1). First, be aware of the difference between the two: (function () {//code}) is an expression, function () {//code} is a functional declaration.
      (2). Second, JS "precompiled" features: JS in the "precompilation" phase, will explain the function declaration, but will ignore the expression.
      (3). When JS executes to function () {//code} (), JS skips function () {//code} and attempts to execute () because function () {//code} has been interpreted in the "precompiled" stage;
      When JS executes to (function () {//code}) (), because (function () {//code}) is an expression, JS will go to solve it to get the return value, because the return value is a function, so it will be executed.

The biggest use of anonymous functions is to create closures (which is one of the features of the JavaScript language), and you can also build namespaces to reduce the use of global variables.

For example:
var a=1;
(function () {
var a=100;
})();
alert (a); Pop up 1
Three. Step-up Package jquery Plugin

The first step is to define a closure area that prevents the plugin from "polluting".
(function ($) {}) (Window.jquery);

Step two JQuery.fn.extend (object) extension jquery method Authoring Plugin
(function ($) {
$.fn.plugin=function (options) {
Do something
};
}) (Window.jquery);

The third step is to give the plug-in default parameters to implement plug-in functions
(function ($) {
$.fn.plugin=function (options) {
var defaults={
Foreground: ' Red ',
Background: ' Yellow '
};
The options are merged into the defaults, defaults inherits the various properties and methods on the options and assigns all the values to Endoptions
var endoptions=$.extend ({},defaults,options);
This.each (function () {
var $this = $ (this);
$this. CSS ({
BackgroundColor:endOptions.background,
Color:endOptions.foreground
});
});
return this;
};
}) (JQuery);

Last Call Plugin
$ (function () {
$ ("P"). Plugin ({foreground: ' Orange ', background: ' #ccc '});
Invoking a custom plug-in
});
Attention

    1. There is a kind of thing called script compression, the front page to reduce the number of scripts and script size, so you want to compress a class of scripts together, in order to avoid compression when the previous script did not write the last semicolon, resulting in compression after the script can not be used, so start with a semicolon.

    2. function is put in the closure, the outside of the function can not call the inside parameters, more secure.

    3. The plug-in is going to return this, returning the current object, in order to follow the chain-style features of jquery.

      Summarize
    4. Jquery.fn = Jquery.prototype, which is the prototype of the JQuery object. The JQuery.fn.extend () method is a prototype method for extending the jquery object. Add a member method to an object, and the class's Member method must be called by an object of the class, so an instance of the jquery class can use this "member function", such as $ (' P '), by using the JQuery.fn.extend (object) extension. Extend (obj).

    5. Closures can build namespaces to reduce the use of global variables and avoid global pollution.

    6. $.extend () is used to merge the parameters in the plug-in, or to extend the global function, $.fn.extend () is used to add member methods to the object.

    7. Return this returns the object, making it easy to chain-call the jquery method.

Front-End Knowledge | On how jquery writes plugins

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.